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

2019-07-11 13:54发布

问题:

I have an abstract class and his concrete class implementation. What I would like to do is to expose the concrete class inside an iOS application (Objective-C) and use protocols to dispatch the events to a ViewController.

The idea is to add an objective C delegate, that conforms an adHoc protocol, to this concrete Class. Any Idea how to achieve it?

Unfortunately I read that Objective-C++ cannot inherits from a C++ class.

Thank you in advance.

回答1:

an objective c++ class can't inherit from a c++ class but it can contain one

@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


回答2:

Try a has-a relationship. Either the objective C++ object has-a C++ object or vice versa. Then make them aware of each other enough for the objective C++ object to relay messages to the C++ object.



回答3:

If you declared a weak pointer to id, you could declare an abstract delegate (a category in NSObject), then call methods freely in the CPP source. Simply import the file that contains the abstract delegate then implement the methods themselves in the ObjC class, and you get a delegate without declaring an actual delegate.