我将假设在您的两个示例中,独立的行是类接口中定义的属性和实例变量。并且其他代码是从同一个类中的某个方法执行的。
让我们看看会发生什么:
@property (nonatomic, retain) MyObject *myObject;
MyObject *obj = [[MyObject alloc] init]; // Retain count = 1
self.myObject = obj; // Retain count +1 (2), because property is defined
// as retain.
[obj release]; // Retain count -1
在此示例中,一切正常。让我们看看第二个:
MyObject *myObject;
MyObject *obj = [[MyObject alloc] init]; // Retain count = 1
myObject = obj; // Retain count still 1. Assigns never changes
// retain counts.
[obj release]; // Retain count -1 (0), object is now deallocated.
// Any access to it though obj or myObject WILL
// cause a crash.
您实际上可以编写 Objective-C 代码并将其视为几乎 100% 的垃圾回收,您只需要信任自动释放池即可。每当你分配一个对象时,你也应该立即将它交给自动释放池。这样你只需要担心在当前方法结束后保留你想要生存的东西。
你的第一个例子可能是:
@property (nonatomic, retain) MyObject *myObject;
MyObject *obj = [[[MyObject alloc] init] autorelease];
self.myObject = obj; // Implicitly retain through property
你的第二个是:
MyObject *myObject;
MyObject *obj = [[[MyObject alloc] init] autorelease];
myObject = [obj retain]; // Explicitly retained to survive end of method
正如您所见,在分配新对象时只需添加 autorelease,并且始终使用属性将减少内存管理,从而仅在 dealloc 方法中释放实例变量。