Iphone 为方法传递块

Iphone 为方法传递块,iphone,objective-c,grand-central-dispatch,Iphone,Objective C,Grand Central Dispatch,我想将不同的块传递到一个方法中。该方法随后将使用传入的块作为参数来分派\u async 我的区块声明如下: typedef int (^ComputationBlock)(int); 接受块的类方法实现为: - (void)doSomething:(int)limit withBlock:(ComputationBlock)block; { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_

我想将不同的块传递到一个方法中。该方法随后将使用传入的块作为参数来分派\u async

我的区块声明如下:

typedef int (^ComputationBlock)(int);
接受块的类方法实现为:

- (void)doSomething:(int)limit withBlock:(ComputationBlock)block;
{

 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

   // typical in-lined block for dispatch_async:  
 dispatch_async(queue, ^{
      // do some work here
 });

 // I want to pass in the block as the 2nd parameter to dispatch_async
 // but the compiler will warn me of a type mismatch unless I cast
 // the block like:
 dispatch_async(queue, (dispatch_block_t)block);    
}

@end

将“
block
”参数键入为
dispatch\u block\t
”可以吗?

它可以编译,但不起作用
dispatch\u block\t
块不能接受任何参数,也不能有返回值。

不,这样做不酷——传递给dispatch\u async的块不需要接受任何参数,也不需要返回任何值。把你的积木扔到那是个坏主意(愚弄大自然是不好的)

只需将要调用的块包装到正确类型的块中:

 dispatch_async(queue, ^{ block(0); } );    

(请注意,调用计算块时还需要向其提供一个参数。)

使用_块传递值

__块int返回值

它可以在块中修改

N.B.“ComputationBlock”与其返回类型中的dispatch\u block\t也不匹配:应该是void,实际上是int!旁白:“愚弄大自然是不好的”*微笑*