Return a dispatch_async fetched variable [duplicate] Return a dispatch_async fetched variable [duplicate] multithreading multithreading

Return a dispatch_async fetched variable [duplicate]


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}