Ric
Ric

Reputation: 796

How do I pass data values back out from a Grand Central Dispatch _asych block for use by main thread?

The Title is the whole question. If the _asych block of code produces meaningful work it will in some cases have produced information which the main thread would now like to use.

In this bare example, how would you get the data value, the string data, contained in myData out of the block for the main thread to work with:

dispatch_queue_t myQueue = dispatch_queue_create("com.mycompany.myqueue", 0); 
dispatch_async(myQueue, ^{                                                    
NSString *myData = [self getSavedData];
});
dispatch_async(myQueue, ^{ dispatch_release(myQueue); });        

Please extend the code help to show me, in simple usage, where and how this NSLog, or its correct equivalent, would be placed in the main thread of the program relative to the GCD block:

NSLog(@"%@", myData);

Upvotes: 0

Views: 286

Answers (1)

Grzegorz Adam Hankiewicz
Grzegorz Adam Hankiewicz

Reputation: 7661

You can nest blocks, yet have each run in different threads.

dispatch_queue_t myQueue = dispatch_queue_create("someid", 0);
dispatch_async(myQueue, ^{
        NSString *myData = [self getSavedData];
        dispatch_async(dispatch_get_main_queue(), ^{
                self.someLabel.text = myData;
            });
    });
dispatch_async(myQueue, ^{ dispatch_release(myQueue); });

If your code is long, it's unwieldy to have in nested blocks. So simply call a method inside dispatch_async like [self processData:myData].

Upvotes: 1

Related Questions