以下是我的一些总结,如果有不对的地方希望大家多多指教
我们在官方文档里看到这样的代码:
在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被释放;