What's the purpose of an ivar when a property exists?

Viewed 5779

The following doesn't complain at compilation nor runtime about no name ivar. So why is it so common to see an ivar and @property/@synthesize.

@interface PropTest : NSObject
{
}
@property (retain) NSString *name;
@end

@implementation PropTest
@synthesize name;
@end

int main (int argc, const char * argv[]) {
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  PropTest *p = [[PropTest new] autorelease];
  p.name = @"Hello, World!";
  NSLog(@"%@",p.name);
  [pool drain];
  return 0;
}

This code prints

Hello, World!

In fact, if i access p->name, i get a warning:

warning: instance variable 'name' is @private; this will be a hard error in the future

which indicates that an ivar is created for me if one doesn't exist.

If that's true, what's the point of creating the ivar manually (ignoring the obvious, that there are sometimes valid reasons for not using the g/setter accessor)?

Or asked differently, should i only ever create an ivar for a property when i need to bypass the accessors?

3 Answers
Related