ios开发(八):property

本文详细解释了Objective-C中的属性概念,包括nonatomic、readonly、readwrite、assign、copy、strong、weak等关键字的用途,以及如何实现getter和setter方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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];

}} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值