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;
)};
)};
}
Result:
Incompatible block pointer types passing 'NSDictionary *(^)(void)'
to parameter of type 'dispatch_block_t' (aka 'void (^)(void)')
Any ideas?
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.
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
.
You would then change
- (NSData *) fetchNSDictionary{...}
To something like
- (void)getDictionaryWithDelegate:(NSObject<StuffGetterProtocol> *)delegate{...}
And instead of return dict;
, you would say:
[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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With