Objective C 对类变量的访问用 ./->

Objective C中类变量的声明一般有两种方式:
1)instance variable
2)property方式声明

instance variable方式声明如下:

[cpp]  view plain copy
  1. @interface MyClass : NSObject {  
  2.     NSString *      _name;  
  3. }  
如果你不想使用自动声明的set/get函数,则可以用这种方式。

instance variable又有@public,@protected和@private之分,这跟C++是一样的。
例子:

[cpp]  view plain copy
  1. @interface MyClass : NSObject {  
  2.  @public  
  3.     NSString *      _name;  
  4. }  
  5.   
  6. 调用:  
  7. MyClass * myClass = [[MyClass alloc] init];   // 这里也可以用[MyClass new]来代替。  
  8. myClass->_name = @"wang";  // Notice that here you need to use "->" to access.  

property方式声明
其实就自动加了set/get函数,如果
[cpp]  view plain copy
  1. @property(retain) NSMutableArray *namearray;  
retain表示会自动增加引用计数。相当于
[cpp]  view plain copy
  1. - (void)setNamearray:(NSMutableArray *)namearray  
  2. {  
  3.     [_namearray autorelease];  
  4.     [namearray retain];  
  5.     _namearray = namearray;  
  6. }  

注意点:
在init函数中变量的初始化不要用proterty的方式,理由见apple document:

Setter methods can have additional side-effects. They may trigger KVC notifications, or perform further tasks if you write your own custom methods.

You should always access the instance variables directly from within an initialization method because at the time a property is set, the rest of the object may not yet be completely initialized. Even if you don’t provide custom accessor methods or know of any side effects from within your own class, a future subclass may very well override the behavior.

大致意思是说如果你的子类override了set函数,会有很多不可预料的behavior在此set函数中,可能会导致执行错误。所以在init方法中,最好使用instance variable方式来初始化。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值