Auto-synthesized ivar in Objective-C is full of traps

The modern Objective-C 2.0 runtime introduces the feature of property with the backing ivars variable generated automatically.
Sounds like a nice feature but you can easily fall into traps if it is not used properly.
Consider the following code:

@interface Person : NSObject
@property (retain) NSString *name;
@end

Sound nice, but the problem with this code is that the ivar that gets generated by default from this code is simply called ‘name’ and it allows for easy slips with forgetting accessing the ivar directly to be written:

-(void)foo{
   // Direct ivar access bypassing property accessors
   name = [NSString stringWithString:@"John"];
}

Note that the string returned from ‘stringWithString’ is auto-released, it would give all sorts of troubles later, possibly crash as the autoreleased variable is never retained and the synthesized property setter is never called.

As you might see some code from the XCode project template, the code uses a style that attach an underscore character as prefix to the backing ivar name, like following code:

@implementation MyUIViewController
@synthesize window = _window;

I don’t think this is good enough. You can still easily screw up yourself by writing code like:

     // compiler doesn't stop you like this
     _name = [NSString stringWithString:@"John"];

In my opinion, the only complete solution is that the backing ivar is completely hidden from the programmer and the generated name will be decorated internally and be known only the compiler, very much like it works in C#.

In that case, statement like this

      name = [NSString stringWithString:@"John"];

should be translated to the equivalent of the below code. (given the correct scope resolution)

      self.name = [NSString stringWithString:@"John"];

Reference:

Advertisement

One Response to Auto-synthesized ivar in Objective-C is full of traps

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s