Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 613
Jakub Arnold Avatar asked Jan 09 '12 15:01

Jakub Arnold


2 Answers

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.

like image 149
Benedict Cohen Avatar answered Sep 22 '22 13:09

Benedict Cohen


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.

like image 28
Jim Avatar answered Sep 22 '22 13:09

Jim