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?
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.
来源:https://stackoverflow.com/questions/9741820/inherit-nsobject-from-c-class