Objective-C类变量的声明

Objective C中类变量的声明一般有两种方式:

1)instance variable
2)property方式声明

instance variable方式声明如下:

@interface MyClass : NSObject {
    NSString *      _name;

如果你不想自己声明set/get函数,则可以用这种方式。

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

例子:

@interface MyClass : NSObject {
 @public
    NSString *      _name;

调用:
MyClass * myClass = [[MyClass alloc] init];  // 这里也可以用[MyClass new]来代替。
myClass->_name = @"wang";  // Notice that here you need to use "->" to access.

property方式声明
其实就自动加了set/get函数,如果

@property(retain) NSMutableArray *namearray;

retain表示会自动增加引用计数。相当于

- (void)setNamearray:(NSMutableArray *)namearray
{
    [_namearray autorelease];
    [namearray release];
    _namearray = namearray;
}

注意点:
在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方式来初始化。

相关推荐