用@property,@synthesize来代替get,set方法,用起来很简单,可以省掉很多的代码量,当需要用SET,GET方法的地方,我们可以用@property,@synthesize来简单的代替,这时系统会自动给我们生成该变量的set,get方法,@property对应方法的声明部分,@synthesize对应方法的实现部分,也就是说@property和@synthesize是成对的出现的。
下面我们就举例说明一下:
//1. ClassTest1.h #import <Foundation/NSObject.h> @interface ClassTest1: NSObject { int test; } @property int test; @end @property相当于在.h头文件中声明了 test的get和set方法,但是没有实现。 #import <Foundation/NSObject.h> @interface ClassTest1: NSObject { int test; -(void)setTest; -(int)test; }@end 下面看下@synthesize //ClassTest1.m #import "ClassTest1.h" @implementation ClassTest1 @synthesize test; @end @synthesize相当于在.m文件中现实了.h头文件中的get和set方法。 //ClassTest1.m #import "ClassTest1.h" @implementation ClassTest1 -(void)setTest:(int)newTest { test = newTest; } -(int)test { return test; } @end与@property相应的还有一些参数读写属性: (readwrite/readonly)setter语意:(assign/retain/copy)原子性: (atomicity/nonatomic)
//1. ClassTest1.h #import <Foundation/NSObject.h> @interface ClassTest1: NSObject { int test; } @property (readonly) int test; @end
意思是 test属性只能读取,不可以改写。
如果使用多线程,有时会出现两个线程互相等待对方导致锁死的情况。在默认情况下(atomic),会防止这种线程互斥出现,但是会消耗一定的资源。所以如果不是多线程的程序,打上(nonatomic)即可,这样可以提交程序的性能。
assign 默认类型,setter方法直接赋值,而不进行retain操作,基本上是为简单数据类型准备的而不是NS对象们。
retain ,copy一般只用于NS对象
//1. ClassTest1.h #import <Foundation/NSObject.h> @interface ClassTest1: NSObject { Test* test; } //@property(nonatomic,retain)Test* test; @property(nonatomic ,copy)Test* test; @end先说对get方法的作用: (以上//标示 两种情况只能出现一种 是或的关系)
带有noatomic的起到的作用,一定要对比下面的来理解
-(Test*) test { return test } 不带有noatomic 参数的property
//1. ClassTest1.h #import <Foundation/NSObject.h> @interface ClassTest1: NSObject { Test* test; } //@property(retain)Test* test; @property(copy)Test* test; @end 则相当于 (以上//标示 两种情况只能出现一种 是或的关系)
-(Test*) test { [test retain]; return [test autorelease]; } 下面对set方法的分析:
//1. ClassTest1.h #import <Foundation/NSObject.h> @interface ClassTest1: NSObject { Test* test; } //@property(noatomic,retain)Test* test; @property(retain)Test* test; @end (以上//标示 两种情况只能出现一种 是或的关系)
对应的set方法:
-(void) test:(Test *)newTest { if(test!=newTest){ [test release]; test = [newTest retain]; } }如果是copy的话:
//1. ClassTest1.h #import <Foundation/NSObject.h> @interface ClassTest1: NSObject { Test* test; } //@property(noatomic,copy)Test* test; @property(copy)Test* test; @end 那么对应的get方法其实为:
-(void) test:(Test *)newTest { if(test!=newTest){ [test release]; test = [newTest copy]; } }
copy与retain的区别:
A:Copy是创建一个新对象,retain是创建一个指针,引用对象计数加1。
B:Copy属性表示两个对象内容相同,新的对象retain为1 ,与旧有对象的引用计数无关,旧有对象没有变化。copy减少对象对上下文的依赖。
retain是复制一个指针,指向的对象的retainCount会+1。