以下是我的一些總結,如果有不對的地方希望大家多多指教
我們在官方文檔裡看到這樣的代碼:
在MyClass.h檔案中
@interface MyClass : NSObject { MyObject *myObject; }
@property (nonatomic, retain) MyObject *myObject;
@end
在MyClass.m檔案中
@synthesize myObject;
-(id)init{
if(self = [super init]){
MyObject * aMyObject = [[MyObject alloc] init];
self.myObject = aMyObject;
[aMyObject release];
}
return self;
}
為什麼要用之上的賦值方法呢?難道self.myObject = [[MyObject alloc] init]; 或者 myObject = [[MyObject alloc] init]; 不可以嗎;不要以訛傳訛,以下是我的一些見解。
第一種:當加上self.的時候..................................
MyObject * aMyObject = [[MyObject alloc] init]; //aMyObject retainCount = 1;
self.myObject = aMyObject; //myObject retainCount = 2;
[aMyObject release]; //myObject retainCount = 1;
第二種:當不加self.的時候
MyObject * aMyObject = [[MyObject alloc] init]; //aMyObject retainCount = 1;
myObject = aMyObject; //myObject retainCount = 1;
[aMyObject release]; //myObject被釋放;