从目标C传递一个块到C ++方法 [英] Pass a block to a C++ method from objective C
问题描述
我有一个C + +辅助类,我使用与目标C。我想从视图控制器(回调)传递c ++类的一个块,以便当它被执行时,我在主线程,并可以更新UI。我当前有一个类似的系统使用函数指针和 performSelector
时调用该函数。我想要一个如何设置c ++变量以及如何传递一个目标C块并从c ++类调用它的示例。
I have a C++ helper class that I use with objective-C. I would like to pass the c++ class a block from a view controller (a callback) so that when it is executed I am on the main thread and can update the UI. I currently have a similar system working with function pointers and performSelector
when the function is called. I would like an example of how to set up the c++ variable and how to pass an objective-C block to it and call it from the c++ class.
如果这是不可能,你能想到另一个/更好的解决方案吗?
If this is not possible, can you think of another/better solution?
推荐答案
所以只是你不完全熟悉块语法?如果是这样,这是一个快速的例子,如果你已经熟悉函数指针(语法或多或少相同,但使用 ^
为声明一个[创建一个闭包是,当然是不同的]。
So is it just that you're not entirely familiar with the block syntax? If so, here's a quick example that should hopefully make sense if you're already familiar with function pointers (the syntax is more or less the same, but with the use of an ^
for declaring one [creating a closure is, of course, different]).
你可能想为块类型设置一个typedef只是为了保存自己重复同样的事情一遍又一遍,但我包括使用typedef的例子,只是把块类型本身放在参数中。
You probably want to set up a typedef for the block types just to save yourself repeating the same thing over and over, but I included examples for both using a typedef and just putting the block type itself in the parameters.
#import <Cocoa/Cocoa.h>
// do a typedef for the block
typedef void (^ABlock)(int x, int y);
class Receiver
{
public:
// block in parameters using typedef
void doSomething(ABlock block) {
block(5, 10);
}
// block in parameters not using typedef
void doSomethingToo(void (^block)(int x, int y)) {
block(5, 10);
}
};
int main (int argc, char const *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Receiver rcv;
// pass a block
rcv.doSomething(^(int x, int y) { NSLog(@"%d %d", x, y); });
rcv.doSomethingToo(^(int x, int y) { NSLog(@"%d %d", x, y); });
[pool drain];
return 0;
}
这篇关于从目标C传递一个块到C ++方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!