如何从 Grand Central Dispatch _asych 块传回数据值以供主线程使用?
标题是整个问题。如果 _asych 代码块产生有意义的工作,那么在某些情况下它会产生主线程现在想要使用的信息。
在这个简单的示例中,如何从主线程的块中获取 myData 中包含的数据值(字符串数据):
dispatch_queue_t myQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_async(myQueue, ^{
NSString *myData = [self getSavedData];
});
dispatch_async(myQueue, ^{ dispatch_release(myQueue); });
请扩展代码帮助,以简单的用法向我展示此 NSLog 的位置和方式或其正确的等效项将被放置在相对于 GCD 块的程序的主线程中:
NSLog(@"%@", myData);
The Title is the whole question. If the _asych block of code produces meaningful work it will in some cases have produced information which the main thread would now like to use.
In this bare example, how would you get the data value, the string data, contained in myData out of the block for the main thread to work with:
dispatch_queue_t myQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_async(myQueue, ^{
NSString *myData = [self getSavedData];
});
dispatch_async(myQueue, ^{ dispatch_release(myQueue); });
Please extend the code help to show me, in simple usage, where and how this NSLog, or its correct equivalent, would be placed in the main thread of the program relative to the GCD block:
NSLog(@"%@", myData);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以嵌套块,但每个块都在不同的线程中运行。
如果您的代码很长,则嵌套块会很不方便。因此,只需调用
dispatch_async
内部的方法,如[self processData:myData]
即可。You can nest blocks, yet have each run in different threads.
If your code is long, it's unwieldy to have in nested blocks. So simply call a method inside
dispatch_async
like[self processData:myData]
.