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中的视频.
| 归档时间: |
|
| 查看次数: |
70093 次 |
| 最近记录: |