object-c学习笔记:属性变量(property)
什么是property?
是一种代码生成机制,能够生成不同类型的getter/setter函数,特别是如果你想要用点(.)操作符号来存取变量的话,你就能必须使用property。
如何使用?
用法是固定的,注意下property后面小括号了跟的参数列表,nonatomic代表非原子性,既不支持多线程的同步,mac上可以根据具体情况考虑,IPhone上就加上把,retain代表对setter的对象加上一个retain操作,同时也会release原有的object,copy顾名思义就是copy setter中参数的对象。看下面的例子:
代码
@interface Engine : NSObject
{
}
@end
@implementation Engine
- (NSString*) description
{
return (@"engine");
}
@end
@interface Tier : NSObject
{
}
@end
@implementation Tier
- (NSString*) description
{
return (@"tier");
}
@end
@interface Car : NSObject
{
int tier_num;
float engine_power;
NSString* name;
Engine* engine;
Tier* tier;
}
@property (nonatomic) int tier_num;
@property (nonatomic) float engine_power;
@property (nonatomic, copy) NSString* name;
@property (nonatomic, retain) Engine* engine;
@property (nonatomic, retain) Tier* tier;
@end
@implementation Car
@synthesize tier_num;
@synthesize engine_power;
@synthesize name;
@synthesize engine;
@synthesize tier;
- (id) init
{
if (self = [super init]) {
tier_num = 4;
engine_power = 100;
name = @"BMW";
}
return self;
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Car* car = [[Car alloc] init];
NSLog(@"number of tiers is %d\n", car.tier_num);
NSLog(@"car's name is %a\n", car.name);
car.name = @"Mazd";
Engine* newEngine = [[Engine alloc] init];
car.engine = newEngine;
// insert code here...
[pool drain];
return 0;
}
额外的内容
默认的propety变量,总是可读写的,如果需要只读控制,就用readonly,这时编译器不会生成setter方法,如
@property (readonly) float something;