如何使用设置自动释放池
您好我正在使用[NSThread detachNewThreadSelector:toTarget:withObject:]我得到了很多的内存泄漏,因为我没有autorelease池设置分离的线程。 我只是想知道我在哪里做这个? 是我打电话之前吗?
[NSThread detachNewThreadSelector:toTarget:withObject:]
或者在正在另一个线程中运行的方法中?
任何帮助将不胜感激,一些示例代码将是伟大的。
谢谢。
在你调用线程的方法…即给出这个…
[NSThread detachNewThreadSelector:@selector(doStuff) toTarget:self withObject:nil];
你的方法是…
- (void)doStuff { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; //Do stuff [pool release]; }
您必须在您调用的方法中设置一个autorelease池,并在新的分离线程中执行。
例如:
// Create a new thread, to execute the method myMethod [NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
和
- (void) myMethod { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Here, add your own code // ... [pool drain]; }
请注意,我们使用排水,而不是autoreleasepool释放。 在iOS上,它没有区别。 在Mac OS X上,如果您的应用程序被垃圾回收,则会触发垃圾回收。 这使您可以编写可以更轻松地重新使用的代码。
创build新的线程:
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
创build由新线程调用的方法。
- (void)myMethod { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Your Code [pool release]; }
如果你需要在新线程内部对主线程做些什么(例如,显示一个加载符号)呢? 使用performSelectorOnMainThread。
[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];
请参阅: – iPhone SDK示例
用你打电话的方法来做。 从本质上讲,你应该设置被调用的方法作为一个独立的工作单元(事实上,它将兼容通过[NSOperation][1]
或Grand Central Dispatch调用:两种更好的组织方式同时工作)。
但是如果我不能改变我在一个新线程上调用的方法的实现呢?
在这种情况下,你会这样做:
[NSThread detachNewThreadSelector: @selector(blah:) toTarget: obj withObject: arg]
要做到这一点:
[NSThread detachNewThreadSelector: @selector(invokeBlah:) toTarget: self withObject: dict] - (void)invokeBlah: (id)dict { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; id obj = [dict objectForKey: @"target"]; id arg = [dict objectForKey: @"argument"]; [obj blah: arg]; [pool release]; }
而不是使用字典,你也可以创build一个封装远程对象调用的NSInvocation 。 我只是select了一本字典,因为它是以最快的方式在SO回答中显示情况。 要么工作。
该文档指出,线程中运行的方法必须创build并销毁自己的autorelease池。 所以如果你的代码有
[NSThread detachNewThreadSelector:@selector(doThings) toTarget:self withObject:nil];
该方法应该是
- (void)doThings { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; //Do your things here [pool release]; }