Inherit NSObject from C++ class

▼魔方 西西 提交于 2019-12-05 16:59:51

You cannot mix inheritance between C++ and Objective-C classes.

Instead, just make a standard Objective-C++ object which wraps your C++ object. Teach the Obj-C object how to pass everything through to your C++ object.

Nope, not possible.

C++ and Objective-C classes are implemented in very different ways. C++ uses a vtable for function lookup, and is static.

Objective-C, however, uses a dynamic dictionary-lookup, and methods can be added at runtime.

However, you could use object composition to do what you want:

// MyCPPClass.cpp
class MyCPPClass {
    int var;

public:
    void doSomething(int arg)
    {
        var += arg;
        std::cout << "var is: " << var << std::endl;
    }
};

// MyCPPWrapper.h
#ifndef __cplusplus
typedef void MyCPPClass;
#endif

@interface MyCPPWrapper : NSObject
{
    @public
    MyCPPClass *cppObject;
}

-(void) doSomething:(int) arg;

@end

// MyCPPWrapper.mm
@implementation MyCPPWrapper

-(void) doSomething:(int)arg
{
    if (cppObject)
        cppObject->doSomething(arg);
}

@end

// main.mm
int main(int argc, const char * argv[])
{
    @autoreleasepool {
        MyCPPWrapper *cppWrapper = [MyCPPWrapper new];
        cppWrapper->cppObject = new MyCPPClass();

        [cppWrapper doSomething:10];
        [cppWrapper doSomething:15];
    }

    return 0;
}

In the MVC design pattern, your controller should be managing how your model is represented in the table view. So, you can just keep your C++ object, your TableViewController will have a pointer to it, and the TableViewController will decide how things show up in the table view.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!