ios开发(八):property

property的作用就是为变量产生一个get一个set,一个property使用由两个部分组成,一个是声明一个是定义,

声明的结构:

@property (attributes) type name;    

nonatomic.  告诉编译器不用保证线程安全。

readonly.   只可读,这个很好理解,也就是只有get,没有set。

readwrite.  这个是默认的方式。

assign.     直接用等于号赋值,这个也是默认方式。

copy.   使用object自己的拷贝函数而不是assign。


iOS 5 中对属性的设置新增了strong 和weak关键字来修饰属性

strong 用来修饰强引用的属性;

@property (strong) SomeClass * aObject; 
对应原来的 
@property (retain) SomeClass * aObject; 和 @property (copy) SomeClass * aObject; 

weak 用来修饰弱引用的属性;
@property (weak) SomeClass * aObject; 
对应原来的 
@property (assign) SomeClass * aObject; 



@property (nonatomic, copy) NSString* name

can be realized by the compiler as follows:

-(NSString*) name{returnname;

}
-(void) setName:(NSString*) aName{

if(name!= aName){[name release];name = [aName copy];

}} 


@property (nonatomic, retain) Employee* manager

can be realized by the compiler as follows:

-(Employee*) manager{returnmanager;

}

-(void) setManager:(Employee*) theManager{if(manager!= theManager){

    [manager release];
    manager = [theManager retain];
  }



@property (nonatomic, assign) NSString* address

can be realized by the compiler as follows:

-(NSString*) address{returnaddress;

}

-(void) setAddress:(NSString*)anAddress{

address = anAddress;



@property (nonatomic, copy) NSMutableArray* achievements
When dealing with mutable collections such asNSMutableArray,the compiler-providedsetter/getter might not be appropriate. Let us see a possible synthesis of theachievementsproperty:

-(NSMutableArray*) achievements{returnachievements;

}
-(void) setAchievements:(NSMutableArray*) newAchievements{

if(achievements!= newAchievements){[achievements release];
achievements = [newAchievements copy];

}} 


你可能感兴趣的:(ios开发(八):property)