据我了解,使用 alloc、new 或 copy 创建的任何内容都需要手动释放。例如:
int main(void) {
NSString *string;
string = [[NSString alloc] init];
/* use the string */
[string release];
}
不过,我的问题是,这不是同样有效吗?:
int main(void) {
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
NSString *string;
string = [[[NSString alloc] init] autorelease];
/* use the string */
[pool drain];
}
最佳答案
是的,您的第二个代码片段完全有效。
每次-autorelease 被发送到一个对象,它被添加到最里面的自动释放池。当池耗尽时,它只是向池中的所有对象发送-release。
自动释放池只是一种方便,它允许您将发送 -release 推迟到“稍后”。 “稍后”可能发生在多个地方,但在 Cocoa GUI 应用程序中最常见的是在当前运行循环周期结束时。
https://stackoverflow.com/questions/65427/