@property是Objective-C语言关键词,与@synthesize配对使用。从iOS5.0(xcode4.5)以及之后的版本,@synthesize能够省略。css
在 ios5.0后,@synthesize省略不写,此时在. h 文件中只写@ property 便可,编译器会自动生成相应的实例变量,实例变量的名字是属性名称前加下划线.如 name = _name;
@property会对对应的变量默认生成相应的getter和setter方法,name = _name;表示在getter和setter中使用的变量名都为_name。getter和setter方法能够重写。html
声明property的语法为:
@property (参数1,参数2) 类型 名字;
好比:
@property(nonatomic,copy) NSString *string;
其中参数主要分为三类:
- 读写属性: (readwrite/readonly)
- setter语意:(assign/retain/copy)
- 原子性: (atomicity/nonatomic)ios
一、 xcode
@property(nonatomic,retain)NSObject *ob; @property(nonatomic ,copy)NSObjejct *ob;
等效代码:ruby
-(NSObject *)ob { return ob; }
二、多线程
@property(retain)NSObject *ob; @property(copy)NSObject *ob;
等效代码:app
-(NSObject *)ob { [ob retain]; return [ob autorelease]; //非ARC中 }
一、性能
@property(nonatomic,retain)NSObject *ob; @property(retain)NSObject *ob;
等效于:ui
-(void)setOb:(NSObject *)newOb { if ( ob != newOb ) { [ob release]; //非ARC // ob = nil; //ARC ob = [newOb retain]; } }
二、atom
@property(nonatomic,copy)NSObject *ob; @property(copy)NSObject *ob;
等效于:
-(void)setOb:(NSObject *)newOb { if (thetest!= newThetest) { [ob release];//非ARC //ob = nil; //ARC thetest= [newOb copy]; } }
非gc的对象,因此默认的assign修饰符是不行的。那么何时用assign、何时用retain和copy呢?推荐作法是NSString用copy,delegate用assign(且必定要用assign,不要问为何,只管去用就是了,之后你会明白的),非objc数据类型,好比int,float等基本数据类型用assign(默认就是assign),而其它objc类型,好比NSArray,NSDate用retain。 [ http://www.cnblogs.com/andyque/archive/2011/08/03/2125728.html ]
在@property 声明NSString变量类型的时候, 通常使用copy,而不是用retain.
是由于不想改变setter传来的原变量。
@interface Man
@property (nonatomic, retain) NSString *name;
@end
-(void)setName:(NSString *)newName { if ( name != newName ) { [name release]; //非ARC // name = nil; //ARC name = [newName retain]; } }
Man *man = [[Man alloc] init];
NSMutableString *newName = [[NSMutableString alloc] initWithString:@"XiaoMing"]; man.name = newName; NSLog( @"the man's name is %@", man.name ); [newName appendString:@"Zhang"]; NSLog( @"the man's name is %@", man.name );
这时name就会受到newName变化的影响,因此我以为前面引用的博客中说 “而其它objc类型,好比NSArray,NSDate用retain”,我以为是不对的,此类型应该使用copy。 不知是否正确,请你们指教。