Search code examples
objective-cpropertiessynthesize

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?


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.