如何通过参数将块作为选择器传递给performSelector:withObject :? [英] How to pass a block as selector with param to performSelector:withObject:?

查看:77
本文介绍了如何通过参数将块作为选择器传递给performSelector:withObject :?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个块变量作为接受参数的选择器,并将其传递给performSelector:withObject :?当前,编写一些测试,并希望编写一个包含所有相关检查的自包含方法.需要通过一个块,在其中接受参数并在该块中进行一些检查.我正在寻找类似的东西:

Is it possible to create a block variable as selector accepting parameters, and to pass it to performSelector:withObject:? Currently, writing some tests and want to write a self contained method with all related checking. Need to pass a block, receive the param in it and do some checking in that block. I'm looking for something like:

...
SEL blockAsSelector = ^{(NSString *param){NSLog(@"Passed param = %@", param);}}

[self performSelector:blockAsSelector withObject:stringThatWillBeUsedAsParamInBlock];
...

推荐答案

是否可以创建一个块变量作为接受参数的选择器,并将其传递给performSelector:withObject :?

Is it possible to create a block variable as selector accepting parameters, and to pass it to performSelector:withObject:?

不.块和选择器不是一回事.

No. Blocks and selectors are not the same thing.

在您的示例中,这没有任何意义. -performSelector:withObject:在同一线程上同步运行.您最好只执行该块,即

In your example, it doesn't make sense. -performSelector:withObject: runs synchronously on the same thread. You might as well just execute the block i.e.

void (^myBlock)(NSString*) = ^(NSString *param){NSLog(@"Passed param = %@", param);};

myBlock(@"foo");

如果要同时执行该块中的工作,则可以使用GCD或amBBOperation.

If you want to do the work in the block concurrently, you would use GCD or am NSBlockOperation.

这篇关于如何通过参数将块作为选择器传递给performSelector:withObject :?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆