返回dispatch_async提取的variables

基本上:一个方法需要返回一个在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; )}; )}; } 

结果:

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

有任何想法吗?

当你说return dict; ,你实际上是试图返回dict调度块的调用者(运行后台asynchronous的自动化过程) – 这是行不通的。

由于您使用的是asynchronous方法,因此无法将数据块中收到的数据返回到您启动networking操作的方法中。当调用该模块中的代码时,系统将长时间执行该方法。

你需要做的是build立一个委托系统 – 如果这是一个辅助类,你可以添加一个协议,包括像didFinishLoadingStuff:(NSDictionary *)stuff

你会改变

  - (NSData *) fetchNSDictionary{...} 

像这样的东西

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

而不是return dict; ,你会说:

 [delegate didFinishLoadingStuff:dict]; 

当然,在你调用这个类的任何类中实现委托方法:

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