在iOS中的dispatch_async和块

这段代码是什么意思?

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ TMBaseParser *parser=[[TMBaseParser alloc] init]; parser.delegate=self; NSString *post =nil; NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding]; [parser parseForServiceType:TMServiceCategories postdata:postData]; }); 

请简单解释一下。谢谢

这段代码

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ }); 

在后台线程上asynchronous运行。 这样做是因为parsing数据可能是一个耗时的任务,它可能会阻塞主线程,从而阻止所有的animation,并且应用程序不会响应。

如果您想了解更多信息,请阅读苹果Grand Central Dispatch的文档

如果上面的代码片段不起作用,那么试试这个:

Objective-C的:

 dispatch_async(dispatch_get_main_queue(), ^{ }); 

有时甚至后台线程不会能够更新用户界面,在那里你必须强制主线程执行代码到主队列。 “^”符号表示块的开始。

Swift 3:

 DispatchQueue.global(qos: .background).async { print("This is run on the background queue") DispatchQueue.main.async { print("This is run on the main queue, after the previous code in outer block") } } 

这是一个Grand Central Dispatch块。

  1. dispatch_async是在另一个队列上运行的调用。
  2. dispatch_get_global_queue是一个调用来获得具有所需特性的特定队列。 例如,代码可以在DISPATCH_QUEUE_PRIORITY_BACKGORUND上以低优先级运行。
  3. 在块内部,代码什么都不做。 post设置为零。 然后一个消息被发送到零“dataUsingEncoding”。 目标C将所有调用都删除为零。 最后,parsing器发送“nil”postData。
  4. 充其量,这将无能为力。 在最坏的情况下发送parsing器零数据将崩溃。