Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top