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方式來初始化。