使用或不使用 autorelease 不是问题,因为在某些情况下,autorelease 是您通过的唯一方法。问题应该是“为什么不对所有对象使用自动释放,而不是使用保留和释放? ”。
要回答这个问题,您应该首先了解什么是自动释放的正确用途。假设您有一个具有两个属性的类:firstName 和 lastName。每个都有一个 getter 和一个 setter。但是您还需要一个返回 fullName 的方法,将这两个字符串连接成一个全新的字符串:
- (NSString *) fullName {
NSString str = [[NSString alloc]initWithFormat:@"%@ %@", firstName, lastName];
// this is not good until we put [str autorelease];
return str;
}
那张图有什么问题?返回字符串的引用计数为 1,因此如果您不想泄漏,调用者应该在完成后释放它。从调用者的角度来看,他只是请求了一个属性 value fullName
。他不知道他得到了一个在使用后应该释放的全新对象,而不是对类内部持有的 NSString 的一些引用!
If we put the [str release]
before return, the string would be destroyed and the method would return garbage! That's where we use [str autorelease]
, to mark the object for release at a later time (typically when the event processing is done). That way the caller gets his object, and does not have to worry whether he should release it or not.
The convention is to call autorelease on a new object before the method returns it to the caller. Exceptions are methods with names that start with alloc
, new
or copy
. In such cases the callers know that a brand new object is created for them and it is their duty to call release on that object.
Replacing release with autorelease altogether is a bad idea, since the objects would pile up and clog the memory very quickly, especially in loops. The resources on the iPhone are limited, so in order to minimize memory hogging, it is your duty to release the object as soon as you're done with it.