Inherit NSObject from C ++ Class

I am emotionally attached to my C ++ class, but I really want it to go into a table view.

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 one bit.

He tells me that the base specifier should be a class.

Is there any hidden thing I can do?

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

+4
source share
3 answers

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

Instead, just create a standard Objective-C ++ object that wraps your C ++ object. Teach your Obj-C object how to pass everything to your C ++ object.

+11
source

No, It is Immpossible.

The C ++ and Objective-C classes are implemented differently. C ++ uses vtable to search for a function and is static.

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

However, you can 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; } 
+2
source

In the MVC design pattern, your controller must control how your model is presented in a table. That way, you can just save your C ++ object, your TableViewController will have a pointer to it, and the TableViewController will decide how everything is displayed in the table view.

+1
source

Source: https://habr.com/ru/post/1401867/


All Articles