iPhone独立运行的线程

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

[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]; 

我一直在做第二种方式,但我一直在阅读的卫斯理食谱使用第一种。

在我看来,最好的方法是使用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 }); }); 

如果您还没有这样做,请在libdispatch / GCD / blocks上查看WWDC 2010上的video。

iOS中multithreading的最佳方式是使用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 }); }); 

我会尝试所有的技术人员张贴,看看哪个是最快的,但我认为这是做到这一点的最好方法。

 [self performSelectorInBackground:@selector(BackgroundMethod) withObject:nil]; 

我已经在NSThread上添加了一个类别,可以让您轻松地在块中执行线程。 你可以从这里复制代码。

https://medium.com/@umairhassanbaig/ios-how-to-perform-a-background-thread-and-main-thread-with-ease-11f5138ba380