// *** before: ***
// the instance variable, the getter and the setter were written by hand,
// and under manual memory management the setter had to be written correctly
@interface Person : NSObject {
NSString *_name;
int _age;
}
- (NSString *)name;
- (void)setName:(NSString *)name;
- (int)age;
- (void)setAge:(int)age;
@end
@implementation Person
- (NSString *)name {
return _name;
}
- (void)setName:(NSString *)name {
if (_name != name) {
[_name release];
_name = [name copy];
}
}
- (int)age {
return _age;
}
- (void)setAge:(int)age {
_age = age;
}
- (void)dealloc {
[_name release];
[super dealloc];
}
@end
// *** in version 2.0: ***
// @property declares the pair of accessors, @synthesize writes them
@interface Person : NSObject {
NSString *_name;
int _age;
}
@property (nonatomic, copy) NSString *name; // copy: a string is copied
@property (nonatomic, assign) int age; // assign: a plain number
@property (nonatomic, readonly) NSString *card; // getter only
@end
@implementation Person
@synthesize name = _name; // the accessors are bound to the ivar _name
@synthesize age = _age;
- (NSString *)card { // a readonly property may be written by hand
return [NSString stringWithFormat:@"%@, %d", _name, _age];
}
@end