允许C++抽象类使用 Objective-C 委托

Allow a C++ abstract class to use an Objective-C delegate

本文关键字:Objective-C 委托 C++ 抽象类 允许      更新时间:2023-10-16

我有一个抽象类和他的具体类实现。我想做的是在iOS应用程序(Objective-C)中公开具体类,并使用协议将事件调度到ViewController。

这个想法是添加一个符合 adHoc 协议的目标 C 委托到这个具体的类中。知道如何实现它吗?

不幸的是,我读到Objective-C++不能从C++类继承。

提前谢谢你。

目标 C++ 类不能从 C++ 类继承,但它可以包含一个

@interface DelegateObject : NSObject
{
}
- (id) init;
- (void) do_something: (NSObject*) thing;
@end
struct cpp_thing
{
    // this could be a template if you wished, or you could take a copy
    // or whatever you want
    void do_something(NSObject* thing) { };
};
@implementation DelegateObject
{
    std::shared_ptr<cpp_thing> _cpp;
}
- (id) init
{
    if (self = [super init])
    {
        _cpp = std::make_shared<cpp_thing>();
    }
    return self;
}
- (void) do_something: (NSObject*) thing
{
    _cpp->do_something(thing);
}
@end

尝试建立关系。 目标C++对象要么有C++对象,反之亦然。 然后让它们彼此足够了解,以便目标对象C++对象将消息中继到C++对象。

如果你声明了一个指向id的弱指针,你可以声明一个抽象委托(NSObject中的一个类别),然后在CPP源中自由调用方法。 只需导入包含抽象委托的文件,然后在 ObjC 类中实现方法本身,即可获得委托,而无需声明实际委托。