Reputation: 40492
If I have the method defined below, does the block ("handler") passed to the method get called on the new thread created by NSOperationQueue
? Or does it get called on the thread it was on when passed to methodWithCompletionHandler:
?
-(void)methodWithCompletionHandler:(void (^)(NSString *message))handler
{
// Note: We are currently on thread #1. Calling handler(@"my message") here
// will run on thread #1.
NSBlockOperation* someOp = [NSBlockOperation blockOperationWithBlock: ^{
// do some stuff
}];
[someOp setCompletionBlock:^{
// Note: Now someOp is completing, but it's in thread #2. Does calling the handler
// as below also run in thread #2 or thread #1?
handler(@"Some message.");
}];
NSOperationQueue *queue = [NSOperationQueue new];
[queue addOperation:someOp];
}
Upvotes: 1
Views: 208
Reputation: 8729
From the documentation:
The exact execution context for your completion block is not guaranteed but is typically a secondary thread.
Upvotes: 6
Reputation: 9012
In the example you have posted, the block in someOp would be executed on a different thread.
In general, blocks act just like a regular function. They run on the thread that called them (unless the block itself does something to call another thread etc...)
Upvotes: 3