iphone ios在单独的线程中运行

Mik*_*e S 96 iphone multithreading thread-safety ios

在单独的线程上运行代码的最佳方法是什么?是吗:

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

要么:

    NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                        selector:@selector(doStuff:)
                                                                          object:nil;
[queue addOperation:operation];
[operation release];
[queue release];
Run Code Online (Sandbox Code Playgroud)

我一直在做第二种方式,但我读过的Wesley Cookbook使用的是第一种方式.

Jac*_*ues 243

在我看来,最好的方法是使用libdispatch,即Grand Central Dispatch(GCD).它限制你使用iOS 4及更高版本,但它非常简单易用.在后台线程上进行一些处理然后在主运行循环中对结果执行某些操作的代码非常简单和紧凑:

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Add code here to do background processing
    //
    //
    dispatch_async( dispatch_get_main_queue(), ^{
        // Add code here to update the UI/send notifications based on the
        // results of the background processing
    });
});
Run Code Online (Sandbox Code Playgroud)

如果您还没有这样做,请在libdispatch/GCD/blocks上查看WWDC 2010中的视频.

  • @Joe冒着说你已经知道的事情的风险,你不应该养成编写杀死线程的代码的习惯,从长远来看它不会对你或你的事业有所帮助.有关不杀死线程的原因,请参阅[this post](http://stackoverflow.com/questions/4149146/why-and-when-shouldnt-i-kill-a-thread)(或许多喜欢它). (4认同)