开发者

iPhone sythesizing

开发者 https://www.devze.com 2023-01-26 03:24 出处:网络
Whilst learning Objective C I\'ve gotten used to how the @property and @synthesize works. //usual way @synthesize world;

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


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消