使用[NSThread detachNewThreadSelector:toTarget:withObject:]时如何设置自动释放池

Dar*_*lay 3 iphone multithreading ios

嗨,我正在使用[NSThread detachNewThreadSelector:toTarget:withObject:]而且我收到了很多内存泄漏,因为我没有为分离的线程设置自动释放池.我只是想知道我在哪里这么做?是在我打电话之前

[NSThread detachNewThreadSelector:toTarget:withObject:]
Run Code Online (Sandbox Code Playgroud)

或者在另一个线程中运行的方法?

任何帮助将不胜感激,一些示例代码将是伟大的.

谢谢.

Sim*_*Lee 9

在你用线程调用的方法中...即给定...

[NSThread detachNewThreadSelector:@selector(doStuff) toTarget:self withObject:nil];
Run Code Online (Sandbox Code Playgroud)

你的方法是......

- (void)doStuff {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  //Do stuff
  [pool release];
}
Run Code Online (Sandbox Code Playgroud)

  • 对于ARC,请参阅[此主题](http://stackoverflow.com/questions/7149403/nsthreads-in-automatic-reference-countingarc) (2认同)

Gui*_*ume 6

您必须在您调用的方法中设置一个自动释放池,该池将在新的分离线程中执行.

例如:

// Create a new thread, to execute the method myMethod
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
Run Code Online (Sandbox Code Playgroud)

- (void) myMethod {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Here, add your own code
    // ...

    [pool drain];
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们在autoreleasepool上使用drain而不是release.在iOS上,它没有区别.在Mac OS X上,如果您的应用程序是垃圾回收,它将触发垃圾回收.这允许您编写可以更轻松地重用的代码.


Ada*_*V C 5

创建新线程:

[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
Run Code Online (Sandbox Code Playgroud)

创建新线程调用的方法.


- (void)myMethod
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    // Your Code
    [pool release];
} 

如果您需要从新线程内部对主线程执行某些操作(例如,显示加载符号),该怎么办?使用performSelectorOnMainThread.

[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];
Run Code Online (Sandbox Code Playgroud)

请参阅: - iPhone SDK示例