如何从 Grand Central Dispatch _asych 块传回数据值以供主线程使用?

发布于 2024-12-11 02:13:05 字数 529 浏览 0 评论 0原文

标题是整个问题。如果 _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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痞味浪人 2024-12-18 02:13:05

您可以嵌套块,但每个块都在不同的线程中运行。

dispatch_queue_t myQueue = dispatch_queue_create("someid", 0);
dispatch_async(myQueue, ^{
        NSString *myData = [self getSavedData];
        dispatch_async(dispatch_get_main_queue(), ^{
                self.someLabel.text = myData;
            });
    });
dispatch_async(myQueue, ^{ dispatch_release(myQueue); });

如果您的代码很长,则嵌套块会很不方便。因此,只需调用 dispatch_async 内部的方法,如 [self processData:myData] 即可。

You can nest blocks, yet have each run in different threads.

dispatch_queue_t myQueue = dispatch_queue_create("someid", 0);
dispatch_async(myQueue, ^{
        NSString *myData = [self getSavedData];
        dispatch_async(dispatch_get_main_queue(), ^{
                self.someLabel.text = myData;
            });
    });
dispatch_async(myQueue, ^{ dispatch_release(myQueue); });

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].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文