Reputation: 660
I'm trying to make a network call run in a background thread so it doesn't freeze my app while it's waiting.
The call happens when I do:
nextTime = [myObj getNextTime];
I do an NSLog as soon as I get it, and that one works. However, when I'm outside of the dispatch block, the same NSLog prints out null.
myObj *current = ((myObj *)sortedArray[i]);
__block NSString *nextTime;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
nextTime = [myObj getNextTime];
NSLog(@"inside%@",nextTime);
dispatch_sync(dispatch_get_main_queue(), ^{
});
});
NSLog(@"outside%@",nextTime);
Any ideas why the outer log is printing null? Am I doing something horribly wrong and I just missed it? Thanks!
Upvotes: 1
Views: 553
Reputation: 8200
Your "outside" NSLog
statement should actually go in that inner dispatch_async
block that is set to run on the main thread, because that block will execute after you've set the value of nextTime
. Any code you place below your asynchronous block call will likely execute way before the code inside the block.
Upvotes: 2
Reputation: 130193
That's because you're setting it inside an asynchronous block, and asynchronous blocks return immediately. If you look at the time stamps of the two logs, you'll see that the outer log is actually being posted before both the inner log, and the setting of the variable.
From the GCD docs on dispatch_async()
:
This function is the fundamental mechanism for submitting blocks to a dispatch queue. Calls to this function always return immediately after the block has been submitted and never wait for the block to be invoked. The target queue determines whether the block is invoked serially or concurrently with respect to other blocks submitted to that same queue. Independent serial queues are processed concurrently with respect to each other.
Upvotes: 4