memmons
memmons

Reputation: 40492

Do blocks run on new or original thread?

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

Answers (2)

Ben Trengrove
Ben Trengrove

Reputation: 8729

From the documentation:

The exact execution context for your completion block is not guaranteed but is typically a secondary thread.

http://developer.apple.com/library/ios/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html#//apple_ref/doc/uid/TP40004591-RH2-SW36

Upvotes: 6

Lance
Lance

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

Related Questions