@synthesize

When declaring properties that will be created with the @synthesize directive, it’s natural to use the same name for both the property and the backing member. Something like this:

@interface MyClass : NSObject
{
    NSString* value;
}

@property(nonatomic, retain) NSString* value;

@end
 
@implementation MyClass

@synthesize value;

- (void)dealloc
{
	[value release];
	[super dealloc];
}

@end

Although natural, I feel that this is a mistake.

The Problem

If you inadvertently reference the member instead of the property in a class method (e.g. value = @"Foo"; instead of self.value = @"Foo";) your memory management scheme may become disordered. If you have chosen the same names for the property and backing member, the compiler can’t help you catch this sort of typo.

The Solution

Fortunately, the @synthesize directive makes it easy to back a property with a member of a different name; use this form:

@synthesize foo=bar;

as, for instance:

@interface MyClass : NSObject
{
    NSString* _value;
}

@property(nonatomic, retain) NSString* value;

@end
 
@implementation MyClass

@synthesize value=_value;

- (void)dealloc
{
	[_value release];
	[super dealloc];
}

@end

Now, if you accidentally omit the self inside a member function while accessing value, the compiler will complain, saving you some headaches down the line.

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • Reddit
  • HackerNews
  • del.icio.us
  • Google Bookmarks
  • Slashdot
This entry was posted in iPhone. Bookmark the permalink.

Comments are closed.