iphone ios 在单独的线程中运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3869217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iphone ios running in separate thread
提问by Mike S
What is the best way to run code on a separate thread? Is it:
在单独的线程上运行代码的最佳方法是什么?是吗:
[NSThread detachNewThreadSelector: @selector(doStuff) toTarget:self withObject:NULL];
Or:
或者:
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(doStuff:)
object:nil;
[queue addOperation:operation];
[operation release];
[queue release];
I've been doing the second way but the Wesley Cookbook I've been reading uses the first.
我一直在做第二种方式,但我一直在阅读的韦斯利食谱使用第一种方式。
回答by Jacques
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:
在我看来,最好的方法是使用 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
});
});
If you haven't done so already, check out the videos from WWDC 2010 on libdispatch/GCD/blocks.
如果您还没有这样做,请查看 WWDC 2010 上 libdispatch/GCD/blocks 上的视频。
回答by Kusal Shrestha
The best way for the multithreading in iOS is using GCD (Grand Central Dispatch).
iOS 中多线程的最佳方式是使用 GCD(Grand Central Dispatch)。
//creates a queue.
dispatch_queue_t myQueue = dispatch_queue_create("unique_queue_name", NULL);
dispatch_async(myQueue, ^{
//stuffs to do in background thread
dispatch_async(dispatch_get_main_queue(), ^{
//stuffs to do in foreground thread, mostly UI updates
});
});
回答by Bobby
I would try all the techniques people have posted and see which is the fastest, but I think this is the best way to do it.
我会尝试人们发布的所有技术,看看哪种技术最快,但我认为这是最好的方法。
[self performSelectorInBackground:@selector(BackgroundMethod) withObject:nil];
回答by Umair
I have added a category on NSThread that will let you execute threads in blocks with ease. You can copy the code from here.
我在 NSThread 上添加了一个类别,可以让您轻松地在块中执行线程。你可以从这里复制代码。