在 C++ 中接收 UI 事件类
我正在 iOS 的 Xcode 中编写 Objective-C++。我的项目主要是 C++ 类和一些最高级别的 Objective-C 类。我的 C++ 类包含 Objective-C UI 元素,我需要它们来接收 UI 事件。 UI 元素是否可以直接调用 C++ 成员函数?即,是否存在与此 C++ 函数调用等效的函数:
[control addTarget:object action:@selector(action:) forControlEvents:event];
据我所知,@selector
在这里对我没有帮助。我需要另一种方法来使控件调用我的成员函数 - 是否存在?
目前,我正在使用 Objective-C 接收器类,它是我的 C++ 类的成员,它接收 UI 事件,然后适当地调用我的 C++ 类,但这似乎是实现此目的的一种迂回方式。如果我所描述的不可能,是否有更好的方法来完成我想做的事情?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您已经发现了最简单的解决方案。您可以通过在 C++ 基类中实现 Obj-C/C++ 桥来进一步封装此功能,并从中派生任何业务逻辑类。
还有另一种选择,即在 Objective-C 运行时级别执行此操作。让您的 C++ 类使用 objc_allocateClassPair() 生成新的 Objective-C 类,使用
class_addMethod()
添加处理操作的方法等(请参阅Objective-C运行时参考)我没有看到任何明显的原因让您想走这条路,但了解这一点是件好事。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 withclass_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.