返回dispatch_async获取的变量

Jas*_*erJ 5 multithreading objective-c ios objective-c-blocks

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

- (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;
        )};
    )};
}
Run Code Online (Sandbox Code Playgroud)

结果:

Incompatible block pointer types passing 'NSDictionary *(^)(void)' 
to parameter of type 'dispatch_block_t' (aka 'void (^)(void)')
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Und*_*ndo 5

当你说return dict;,你实际上是在尝试返回dict调度块的调用者(运行后台asyncs的自动化进程) - 这不起作用.

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

你需要做的是设置一个委托系统 - 如果这是一个帮助类,你可以添加一个包含类似方法的协议didFinishLoadingStuff:(NSDictionary *)stuff.

然后你会改变

 - (NSData *) fetchNSDictionary{...}
Run Code Online (Sandbox Code Playgroud)

喜欢的东西

- (void)getDictionaryWithDelegate:(NSObject<StuffGetterProtocol> *)delegate{...}
Run Code Online (Sandbox Code Playgroud)

而不是return dict;,你会说:

[delegate didFinishLoadingStuff:dict];
Run Code Online (Sandbox Code Playgroud)

当然,在您调用它的任何类中实现委托方法:

- (void)didFinishLoadingStuff:(NSDictionary *)stuff
{
    //do something with stuff
}
Run Code Online (Sandbox Code Playgroud)