Question

I'm writing Objective-C++ in Xcode for iOS. My project is mostly C++ classes and a few Objective-C classes at the highest level. My C++ classes contain Objective-C UI elements and I need them to receive UI events. Is it possible for a UI element to call a C++ member function directly? I.e. is there an equivalent to this call for a C++ function:

[control addTarget:object action:@selector(action:) forControlEvents:event];    

From what I understand @selector will not help me here. I would need another way to make the control call my member function - does one exist?

For now, I'm using an Objective-C receiver class, a member of my C++ classes, that receives UI events and then calls my C++ class appropriately, but this seems like a roundabout way of achieving this. If what I've described isn't possible, is there a better way to do what I'm trying to do?

Was it helpful?

Solution

I think you've already discovered the simplest solution. You could further encapsulate this functionality by implementing the Obj-C/C++ bridge in a C++ base class and derive any of your business logic classes from that.

There is another option, which is to do this at the Objective-C runtime level. Have your C++ class generate a new Objective-C class with objc_allocateClassPair(), add a method for handling your action with class_addMethod(), etc. (see the Objective-C Runtime Reference) I don't see any obvious reason why you'd want to go down this route, but it's good to be aware of it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top