Reputation: 400
Supposing I have a code like this:
[ApiConnection getServerTimeWithBlock:^(BOOL gotTimeResponse){
if(gotTimeResponse)
{
//we're online, got the response from time endpoint
[ApiConnection registerNewCustomerWithBlock:^(NSString* val){
if(val)
{
NSLog(@"val: %@",val);
}
else
{
NSLog(@"no val");
}
}];
}
else
{
//we're offline
}
}];
NSLog(@"TEST");
why is the last NSLog executed before the whole first block has finished execution?
Upvotes: 0
Views: 56
Reputation: 119242
Presumably getServerTimeWithBlock:
is exectuted asynchronously. When supplying the block, you're telling the APIConnection object what to do when it has finished getting the server time. This will involve network fetches and reading data back, which you don't want to wait for on the main thread as this will cause your UI to freeze. Your program therefore carries on, and the block is executed whenever the fetch is complete.
Note that blocks do not imply that asynchronous or multithreaded code is in use (see NSArray's enumerateWithBlock: method, for example) but it seems very likely to be the case here.
Upvotes: 2
Reputation: 119021
Because the getServerTimeWithBlock:
method is asynchronous, so it returns immediately and runs on a background thread. When that thread is complete is calls the completion block.
So, the method runs before your log, but the completion block (usually) doesn't (it might if there was an error or something like that).
Upvotes: 4