iphone ios在单独的线程中运行 [英] iphone ios running in separate thread
问题描述
在单独的线程上运行代码的最佳方法是什么?它是:
What is the best way to run code on a separate thread? Is it:
[NSThread detachNewThreadSelector: @selector(doStuff) toTarget:self withObject:NULL];
或者:
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(doStuff:)
object:nil;
[queue addOperation:operation];
[operation release];
[queue release];
我一直在做第二种方式,但我读过的Wesley Cookbook使用的是第一种方式。
I've been doing the second way but the Wesley Cookbook I've been reading uses the first.
推荐答案
在我看来,最好的方法是使用libdispatch,即Grand Central Dispatch(GCD)。它限制你使用iOS 4及更高版本,但它非常简单易用。在后台线程上进行一些处理然后在主运行循环中对结果执行某些操作的代码非常简单和紧凑:
In my opinion, the best way is with libdispatch, aka Grand Central Dispatch (GCD). It limits you to iOS 4 and greater, but it's just so simple and easy to use. The code to do some processing on a background thread and then do something with the results in the main run loop is incredibly easy and compact:
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
});
});
如果您还没有这样做,请查看WWDC 2010上有关libdispatch / GCD /的视频块。
If you haven't done so already, check out the videos from WWDC 2010 on libdispatch/GCD/blocks.
这篇关于iphone ios在单独的线程中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!