假设我有以下情况:
- (void)someFunction:(id)param {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSObject *objectA = [[NSObject alloc] init];
[objectA doStuff]; // Don't need to release objectA because of the pool
if (!someValue) {
[pool release]; // Doubt here
return;
}
NSObject *objectB = [[NSObject alloc] init];
[objectB doStuff]; // Don't need to release objectB because of the pool
[pool release];
}
以这种方式从池区内返回是否正确?
答案 0 :(得分:2)
简答:是的。
答案很长:在没有显式释放的情况下放弃的池在它所嵌套的自动释放池(通常是当前线程的顶级自动释放池)被释放时被释放。
是的,这是错误的:NSObject *objectA = [[NSObject alloc] init];
[objectA doStuff]; // Don't need to release objectA because of the pool
您仍然必须明确地释放已分配的对象:
NSObject *objectA = [[NSObject alloc] init];
[objectA doStuff];
[objectA release];
或将它们添加到自动释放池:
NSObject *objectA = [[[NSObject alloc] init] autorelease];
[objectA doStuff];