0

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.

Community
  • 1
  • 1
chrs
  • 5,906
  • 10
  • 43
  • 74

1 Answers1

5

Either is fine. Using self.property calls the getter or setter method (either synthesized or defined), while _property accesses the instance variable directly.

Since self.property calls a method, it can have side effects. For example:

- (Property *)property {
    if (_property == nil) {
        _property = [[Property alloc] init];
    }
    return _property;
}

Calling self.property will create the a new Property and assign it to _property if it does not exist before returning that value, whereas _property will point to nil if it is accessed before self.property has been called for the first time on a particular instance of this class.

In fact, @property declarations do not have to correspond to instance variables; an implementation of the -property method could create and return a new Property each time it is invoked.

titaniumdecoy
  • 18,900
  • 17
  • 96
  • 133