Inherit NSObject from C++ class

邮差的信 提交于 2019-12-07 08:58:38

问题


I'm emotionally attached to my C++ class, but I really want it to go into a tableview.

Is there a way to subclass NSObject from a standard c++ class?

this is what I tried to do:

class Model : NSObject {
public:
    NSString *key;
};

The compiler did not like it one bit.

It tells me the the base specifier must be a class.

Is there any kind of sneaky thing I can do?

Should I just make it a standard objective C++ object?


回答1:


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.




回答2:


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;
}



回答3:


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.



来源:https://stackoverflow.com/questions/9741820/inherit-nsobject-from-c-class

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