iOS中的dispatch_async和阻止

时间:2013-05-16 14:14:12

标签: 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];
    });

请简要解释一下。

3 个答案:

答案 0 :(得分:101)

中的一段代码
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

});

在后台线程上异步运行。这样做是因为解析数据可能是一项耗时的任务,它可能会阻止主线程停止所有动画并且应用程序无法响应。

如果您想了解更多信息,请阅读Grand Central DispatchDispatch Queue上的Apple文档。

答案 1 :(得分:6)

如果以上代码段不起作用,请尝试以下操作:

<强>目标-C:

dispatch_async(dispatch_get_main_queue(), ^{

});

应始终从主队列执行UI更新。 “^”符号表示块的开始。

斯威夫特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")
    }
}

答案 2 :(得分:2)

这是Grand Central Dispatch block。

  1. dispatch_async是在另一个队列上运行的调用。
  2. dispatch_get_global_queue是一个获取具有所需特征的特定队列的调用。例如,代码可以在DISPATCH_QUEUE_PRIORITY_BACKGORUND上以低优先级运行。
  3. 在块中,代码什么都不做。帖子设置为零。然后将消息发送到nil&#34; dataUsingEncoding。&#34; Objective C drops all calls to nil.最后,解析器被发送&#34; nil&#34; POSTDATA。
  4. 充其量,这无济于事。在最坏的情况下发送解析器nil数据将崩溃。