返回派生的dispatch_async变量 [英] Return a dispatch_async fetched variable

查看:124
本文介绍了返回派生的dispatch_async变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上:方法需要返回在dispatch_async中获取的NSDictionary.这是我尝试过的:

Basically: a method needs to return a NSDictionary that is fetched within a dispatch_async. This is what I have tried:

- (NSDictionary *)fetchNSDictionary {
    dispatch_queue_t Queue = dispatch_queue_create("Dictionary fetcher", NULL);
    dispatch_async(Queue, ^{
        NSDictionary *dict = ...
        dispatch_async(dispatch_get_main_queue(),^{
            return dict;
        )};
    )};
}

结果:

Incompatible block pointer types passing 'NSDictionary *(^)(void)' 
to parameter of type 'dispatch_block_t' (aka 'void (^)(void)')

有什么想法吗?

推荐答案

当您说return dict;时,实际上是在尝试将dict返回给调度块的调用者(运行后台异步的自动过程)-这不起作用.

When you say return dict;, you are actually trying to return dict to the caller of the dispatch block (the automated process that runs background asyncs) - which doesn't work.

由于使用的是异步方法,因此无法将在块中接收到的数据返回到您开始进行网络操作的方法.在调用该块中的代码时,系统已很长时间可以执行该方法.

Since you are using an asynchronous method, you can't return data received in a block back to the method you started the network operation in. By the time the code in that block is called, the system is long done with executing that method.

您需要做的是设置一个委托系统-如果这是一个帮助器类,则可以添加一个协议,其中包括didFinishLoadingStuff:(NSDictionary *)stuff之类的方法.

What you need to do instead is set up a delegate system - if this is a helper class, you could add a protocol including a method like didFinishLoadingStuff:(NSDictionary *)stuff.

然后您将更改

 - (NSData *) fetchNSDictionary{...}

类似

- (void)getDictionaryWithDelegate:(NSObject<StuffGetterProtocol> *)delegate{...}

而不是return dict;,您会说:

[delegate didFinishLoadingStuff:dict];

当然要在您从以下任何类调用的类中实现委托方法:

And of course implement the delegate method in whatever class you are calling this from:

- (void)didFinishLoadingStuff:(NSDictionary *)stuff
{
    //do something with stuff
}

这篇关于返回派生的dispatch_async变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆