我想将不同的 block 传递给一个方法。该方法随后将使用传入的 block 作为 dispatch_async 的参数。
我的 block 声明如下:
typedef int (^ComputationBlock)(int);
接受 block 的类方法实现为:
- (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_block_t
吗?
最佳答案
不,这样做并不酷——传递给 dispatch_async 的 block 不需要接受任何参数并且不返回任何内容。将您的 ComputationBlock 转换到那将是一个坏主意(愚弄大自然是不好的)。
只需将要调用的 block 包装在正确的类型之一中:
dispatch_async(queue, ^{ block(0); } );
(请注意,您还需要在调用 ComputationBlock 时为其提供参数。)
关于iphone - 为方法传递 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4621582/