ios iOS中的dispatch_async和block

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16589823/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:36:51  来源:igfitidea点击:

dispatch_async and block in iOS

iosdispatch-async

提问by Tunvir Rahman Tusher

What this piece of code mean?

这段代码是什么意思?

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

please explain it briefly.

请简要解释一下。

回答by Marcin Kuptel

The piece of code in

这段代码在

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

});

is run asynchronously on a background thread. This is done because parsing data may be a time consuming task and it could block the main thread which would stop all animations and the application wouldn't be responsive.

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

If you want to find out more, read Apple's documentation on Grand Central Dispatchand Dispatch Queue.

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

回答by Md Rais

If the above code snippets doesn't work then, try this:

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

Objective-C:

目标-C:

dispatch_async(dispatch_get_main_queue(), ^{

});

UI updates should always be executed from the main queue. The "^" symbol indicates a start of a block.

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

Swift 3:

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

回答by rismay

That is a Grand Central Dispatch block.

那是一个大中央调度块。

  1. dispatch_async is a call to run on another queue.
  2. dispatch_get_global_queue is a call to get a specific queue with the desired characteristics. For example, the code could be run at a low priority on the DISPATCH_QUEUE_PRIORITY_BACKGORUND.
  3. Inside the block, the code does nothing. Post is set to nil. Then a message is sent to nil "dataUsingEncoding." Objective C drops all calls to nil.Finally, the parser is sent "nil" postData.
  4. At best, this will do nothing. At worst sending the parser nil data will crash.
  1. dispatch_async 是在另一个队列上运行的调用。
  2. dispatch_get_global_queue 是获取具有所需特征的特定队列的调用。例如,代码可以在 DISPATCH_QUEUE_PRIORITY_BACKGORUND 上以低优先级运行。
  3. 在块内,代码什么都不做。帖子设置为零。然后向 nil "dataUsingEncoding" 发送一条消息。Objective C 将所有调用都置为 nil。最后,解析器发送“nil”postData。
  4. 充其量,这不会有任何作用。最坏的情况是发送解析器 nil 数据会崩溃。