Pass a block to a C++ method from objective C

Aran Mulholland picture Aran Mulholland · May 16, 2011 · Viewed 7.2k times · Source

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?

Answer

somebody picture somebody · May 20, 2011

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]).

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;
}