Chapter 6 : 存取器
1. 示例代码:
1 // Car.h文件 2 3 #import <Cocoa/Cocoa.h> 4 5 @interface Car : NSObject 6 { 7 NSString *name; 8 NSMutableArray *tires; 9 Engine *engine; 10 } 11 12 @property (copy) NSString *name; 13 @property (retain) Engine *engine; 14 15 - (void)setTire:(Tire *)tire atIndex:(int)index; 16 - (Tire *)tireAtIndex:(int)index; 17 - (void)print; 18 19 @end
1 // Car.m文件 2 3 #import "Car.h" 4 5 @implementation Car 6 7 @synthesize name; 8 @synthesize engine; 9 10 - (id)init 11 { 12 if (self = [super init]) 13 { 14 name = @"Car"; 15 tires = [[NSMutableArray alloc] init]; 16 17 for (int i = 0; i < 4; i++) 18 { 19 [tires addObject:[NSNull null]]; 20 } 21 } 22 23 return self; 24 } 25 26 - (void)dealloc 27 { 28 [name release]; 29 [tires release]; 30 [engine release]; 31 32 [super dealloc]; 33 } 34 35 - (void)setTire:(Tire *)tire atIndex:(int)index; 36 { 37 [tires replaceObjectAtIndex:index withObject:tire]; 38 } 39 40 - (Tire *)tireAtIndex:(int)index 41 { 42 Tire *tire = [tires objectAtIndex:index]; 43 44 return tire; 45 } 46 47 - (void)print 48 { 49 for (int i = 0; i < 4; i++) 50 { 51 NSLog(@"%@", [self tireAtIndex:i]); 52 } 53 NSLog(@"%@", engine); 54 } 55 56 @end
2. 在类中定义属性:
1 // 在接口中 2 // @interface 3 4 // 表明类对象具有float类型的属性,名称为: rainHanding 5 @property float rainHanding; 6 7 // @end
@property的作用是自动声明属性的setter和getter方法,如上例所示,这样就可以调用-setRainHanding:来设置属性,
调用- (float)rainHanding来访问属性。
1 // @implementation 2 3 // 在.m文件中创建属性的访问器 4 @synthesize rainHanding; 5 6 // @end
有时你可能希望实例变量有另一个名称 ,而公开的属性有另一个名称,方法如下:
1 // @interface 2 { 3 float _rainHanding; 4 } 5 6 @property float rainHanding; 7 8 // @end 9 10 // @implementation 11 12 @synthesize rainHanding = _rainHanding; 13 14 // @end
3. 属性特性:
1 // @interface 2 3 // 对象可读写,对象将被复制 4 @property (readwrite, copy) NSString *name; 5 6 // 对象可读写,对象将被保持 7 @property (readwrite, retain) NSString *name; 8 9 // 对象只读 10 @property (readonly) NSString *name; 11 12 // @end
4. 补充内容:
-> C/C++中支持的内存方式Objective-C都支持(如new、delete或malloc、free), Objective-C也有自己对象分配内存的方法: alloc、allocWithZone。如果出现内存警告(Memory Warning),需要手动清除不必要的内存对象。如果还不够用,内存继续增大,系统将会强制应用退出。
-> 数据类型的字节数对应表: