Reputation: 4852
Is it possible to have a objective c member in a c++ class
@interface ObjectiveCClass : UIViewController {
int someVarialbe;
}
- (void)someFunction;
@end
class CPlusPlusClass{
ObjectiveCClass obj; // have a objective c member
void doSomething(){
obj.someFunction; // and call a objective c method
}
};
Any guidance would really be appreciated.
Cheers
Upvotes: 4
Views: 3029
Reputation: 237060
There's a dialect of Objective-C called Objective-C++ that is interoperable with C++ the same way that Objective-C is interoperable with C. You can either change the setting for the file to be Objective-C++ or change the extension to ".mm". You'll still need to access Objective-C objects through pointers and do the alloc-init dance and all that, of course.
Upvotes: 2
Reputation: 36026
To create header files that can be shared between obj-c and cpp code, you could use the compiler predefined macros to do something like:
// A .h file defining a objc class and a paired cpp class
// The implementation for both the objective C class and CPP class
// MUST be in a paired .mm file
#pragma once
#ifdef __OBJC__
#import <CoreFoundation/CoreFoundation.h>
#else
#include <objc/objc.h>
#endif
#ifdef __OBJC__
@interface ObjectiveCClass :
...
typedef ObjectiveCClass* ObjectiveCClassRef;
#else
typedef id ObjectiveCClassRef;
#endif
#ifdef __cplusplus
class CPlusPlusClass {
ObjectiveCClassRef obj;
void doSomethind();
};
#endif
Im not 100% sure its legal to have ObjectiveCClassRef change type like that between c/cpp and obj-c builds.
But id
is a c/cpp compatible type defined in the objective C header files as capable of storing an objective C class pointer, and, when used in .m or .mm files, allows you to call the object directly using objective C syntax.
Upvotes: 8