块是在新线程还是原始线程上运行?

时间:2013-02-21 22:38:16

标签: iphone objective-c cocoa-touch objective-c-blocks

如果我有下面定义的方法,那么传递给方法的块(“handler”)是否会被NSOperationQueue创建的新线程调用?或者在传递给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];
}

2 个答案:

答案 0 :(得分:6)

来自文档:

  

完成块的确切执行上下文不是   保证,但通常是次要线程。

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

答案 1 :(得分:3)

在您发布的示例中,someOp中的块将在不同的线程上执行。

通常,块的作用就像常规函数一样。它们在调用它们的线程上运行(除非块本身做了一些事情来调用另一个线程等...)