我写了一个小程序来测试是否NSInvocationOperation
会为操作创建一个自动释放池:
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
@end
@implementation MyClass
- (void)performSomeTask:(id)data
{
NSString *s = [[[NSString alloc] initWithFormat:@"hey %@", data]
autorelease];
if ([[NSThread currentThread] isMainThread])
NSLog(@"performSomeTask on the main thread!");
else
NSLog(@"performSomeTask NOT on the main thread!");
NSLog(@"-- %@", s);
}
@end
int main(int argc, char *argv[]) {
MyClass *c = [MyClass new];
if (argc == 2 && strcmp(argv[1], "nop") == 0)
[c performSomeTask:@"ho"];
else {
NSInvocationOperation *op = [[NSInvocationOperation alloc]
initWithTarget:c
selector:@selector(performSomeTask:)
object:@"howdy"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:op];
[op waitUntilFinished];
[op release];
[queue release];
}
[c release];
return 0;
}
它的工作原理如下:如果在命令行上传递“nop”,它将-performSomeTask:
直接在主线程上执行,没有自动释放池。结果输出是:
$ ./c nop
*** __NSAutoreleaseNoPool(): Object 0x10010cca0 of class NSCFString autoreleased with no pool in place - just leaking
performSomeTask on the main thread!
-- hey ho
自动释放的字符串-performSomeTask:
会导致泄漏。
在不传递“nop”的情况下运行程序将-performSomeTask:
通过NSInvocationOperation
另一个线程执行。结果输出是:
$ ./c
*** __NSAutoreleaseNoPool(): Object 0x100105ec0 of class NSInvocation autoreleased with no pool in place - just leaking
*** __NSAutoreleaseNoPool(): Object 0x100111300 of class NSCFSet autoreleased with no pool in place - just leaking
*** __NSAutoreleaseNoPool(): Object 0x100111b60 of class NSCFSet autoreleased with no pool in place - just leaking
*** __NSAutoreleaseNoPool(): Object 0x100105660 of class NSCFSet autoreleased with no pool in place - just leaking
performSomeTask NOT on the main thread!
-- hey howdy
正如我们所看到的,有 和 的实例NSInvocation
正在NSSet
泄漏,但其中的自动释放字符串-performSomeTask:
没有泄漏,因此为该调用操作创建了一个自动释放池。
我认为可以安全地假设NSInvocationOperation
(并且可能是 Apple 框架中的所有NSOperation
子类)创建自己的自动释放池,就像并发编程指南建议的自定义NSOperation
子类一样。