Question

Whilst learning Objective C I've gotten used to how the @property and @synthesize works.

//usual way
@synthesize world;

But recently I've come across practices were @synthesize is like this:

//new way
@synthesize world=world_;

Could someone explain why this technique is used please?

Thanks,

Mark

Was it helpful?

Solution

I believe this is used to avoid confusion between the actual ivar name and the property name. so you can have

@interface MyClass : NSObject
{
    NSObject *_myObjActualIVar;
}
@property (retain) NSObject *myObjProperty;

@end

@implementation MyClass
@synthesize myObjProperty = _myObjActualIVar;

- (void) someMethod: (NSObject *)someOtherObject
{
    [_myObjActualIVar release]; // here I know I'm accessing the ivar

    self.myObjProperty = someOtherObject; // here I know I'm using the setter method

    //myObjProperty = someOtherObject; // if I accidentally try to do this
    //self._myObjActualIVar;           // or this, the compiler will tell me
}

@end

and then it makes it harder for you or some other developer working on this class to inadvertently access the ivar when you actually wanted the property or vice-versa. The different names make it clearer which is which.

OTHER TIPS

from the Objective-C 2 manual:

You can use the form property=ivar to indicate that a particular instance variable should be used for the property, for example:

@synthesize firstName, lastName, age = yearsOld
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top