Property vs. instance variable

Properties are just setters and getters for ivars and should (almost) always be used instead of direct access.

@interface APerson : NSObject {
    // NSString *_name;           //  necessary for legacy runtime
}

@property(readwrite) NSString *name;

@end

@implementation APerson
@synthesize name;                 // use name = _name for legacy runtime
@end

@synthesize creates in this case those two methods (not 100% accurate):

- (NSString *)name {
    return [[_name copy] autorelease];
}
- (void)setName:(NSString *)value {
    [value retain];
    [_name release];
    _name = value;
}

It’s easy now to distinguish between ivars and getters/setters. The accessors have got the self. prefix. You shouldn’t access the variables directly anyway.


Your sample code doesn’t work as it should be:

_myVar = some_other_object;      // _myVar is the ivar, not myVar.
self.myVar = some_other_object;  // works too, uses the accessors

Leave a Comment