Possible Duplicate:
Difference between self.ivar and ivar?
Let’s say I have the following class
@interface
@property ( nonatomic, retain ) MyObject* property;
@end
@implementation
@synthesize property = _property;
-(id) init{
if ((self = [super init])) {
_property = [MyObject new];
self.property = [MyObject new];
NSLog(@"%@", _property.description);
NSLog(@"%@", self.property.description);
}
return self;
}
@end
What is the correct way? using accessors (synthesize: self.property) or using the ivar directly? It’s just that i have sometimes felt that using the accessors caused in errors when I try to use them in other files.
Either is fine. Using
self.propertycalls the getter or setter method (either synthesized or defined), while_propertyaccesses the instance variable directly.Since
self.propertycalls a method, it can have side effects. For example:Calling
self.propertywill create the a new Property and assign it to_propertyif it does not exist before returning that value, whereas_propertywill point to nil if it is accessed beforeself.propertyhas been called for the first time on a particular instance of this class.In fact,
@propertydeclarations do not have to correspond to instance variables; an implementation of the-propertymethod could create and return a new Property each time it is invoked.