Thursday, July 9, 2009

setters/getters vs. properties

In Objective-C it is common to provide accessor (getter) and mutator (setter) methods like in the following:

@interface RunningShoe : NSObject {
// instance variables
NSString* shoeName;
}

// method declarations
-(NSString *) shoeName;
-(void) setShoeName:(NSString*) _someShoeName;

@end

and the implementation:

@implementation RunningShoe

- (void)setShoeName:(NSString *)value {
if (value != shoeName) {
[value release];
name = [value copy];
}
}

@end


This is kind of wordy after a while. Well, there is a simpler alternative called properties:


@interface RunningShoe : NSObject {
NSString* shoeName;
}

// define properties
@property (copy) shoeName;

@end

now the implementation:

@implementation RunningShoe

@synthesize shoeName;
@end

One of the cool things about properties is that they are overidable. You may be happy with the standard getter/setter functionality...but you may want to do something out of the ordinary. Perhaps you want to capitalize a username property before actually assigning it to an instance variable. By overriding the setUsername method you can do this (even though it is a @synthesize property).

No comments:

Post a Comment