Is specifying ivar name to @synthesize considered redundant or a good practice?
Asked Answered
R

3

5

I've watched the Stanford iTunes U course on iOS (cs193p) where the teacher explicitly says to always specify ivar name when using @synthesize to avoid problems, such as

@synthesize name = _name;

But while browsing through the Cocoa documentation on declared properties I haven't really seen this, or in any other sample code.

This brings me to a question, why is this needed? Isn't it good enough to just use the @synthesize with a property name? Are there any specific problems that this can help avoid?

Ribosome answered 9/1, 2012 at 15:47 Comment(1)
possible duplicate of @synthesize ivarName = _ivarName convention, preference or performance?Sleet
P
6

The reason for doing so is to prevent the ivars from being directly accessed and thus causing memory management issues. Eg:

Correct: self.name = newName; Incorrect: name = newName;

The getters and setters of the property ensure that memory management is handled correctly. To access the ivars you must explicitly type the leading underscore, which is very hard to do by accident. The only time to access the ivars directly are in init, dealloc and getters and setters.

Pascual answered 9/1, 2012 at 16:33 Comment(0)
C
1

If you don't specify the ivar name, it will use the same name as the property. So these two are equivalent:

@synthesize name;
@synthesize name = name;

If all you are doing is name = name, then yes, it's entirely redundant.

The reason why people specify things like name = _name is to use a different name for the ivar and the property. One reason for doing this is so you don't get mixed up between the property and the ivar, but frankly, if you aren't clear on the difference, this little tweak isn't going to save you.

Cabasset answered 9/1, 2012 at 16:13 Comment(1)
I'm not sure it's because people are "mixed up", rather to help prevent using the ivar rather than the property by mistake.Yarak
I
0

It is definitely not redundant because @synthesize name = _name; has another meaning than @synthesize name;. Whether you want to name your ivars differently than your properties is largely a matter of personal preference. Both variants are perfectly fine.

Involute answered 9/1, 2012 at 15:49 Comment(1)
But as a newbie to Objective-C, I don't have any personal preference. Is there any reason behind why should I use the longer @synthesize name = _name;? Does it actually change anything if I don't have a custom getter/setter?Ribosome

© 2022 - 2024 — McMap. All rights reserved.