nsautoreleasepool范围内的return语句 [英] return statement inside nsautoreleasepool scope
本文介绍了nsautoreleasepool范围内的return语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我说以下情况:
- (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];
}
以这种方式从池块内部返回是否正确?
Is it right to return from inside the pool block in this way?
推荐答案
简短答案:是.
长答案:被嵌套而没有显式释放的池在释放它嵌套的自动释放池(通常是当前线程的顶级自动释放池)时释放.
Long answer: pool that is abandoned without explicit release is released when the autorelease pool in which it nests (usually current thread's top autorelease pool) is released.
顺便说一句,这是错误的:
Btw, this is wrong:
NSObject *objectA = [[NSObject alloc] init];
[objectA doStuff]; // Don't need to release objectA because of the pool
您仍然必须显式释放分配的对象:
You still have to release allocated objects, either explicitly:
NSObject *objectA = [[NSObject alloc] init];
[objectA doStuff];
[objectA release];
或通过将它们添加到自动释放池中:
or by adding them to autorelease pool:
NSObject *objectA = [[[NSObject alloc] init] autorelease];
[objectA doStuff];
这篇关于nsautoreleasepool范围内的return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文