I was hoping to get some help with a project I'm working on. I'm currently trying to rework this code https://github.com/djwait/CoreBluetoothExample written in Objective -c into Openframeworks ios Objective c++. However I am a complete beginner to Objective -c and am feeling lost as to how to proceed. The aim is to get access to the variable uint16_t heartRate (from the original app) and use it in c++ code. More than anything I’m confused as to how the original code is creating an ACViewController object and as to how its member functions are being called.
My current method has been to copy over the original ACViewController .h to my new project. Then import the ACViewController.h in my ofApp.h, Create a class:
ACViewController *acv;
Then in setup: acv = [[ACViewController alloc]init];
But whenever I try to call a function such as [acv renderHeartRateMeasurement]; i get
Instance method '-renderHeartRateMeasurement' not found (return type defaults to 'id')
Any help would be much appreciated!
Best,
Gustaf
If I understand you correctly, you want to be able to call Objective-C methods from C++.
Let's assume you have an Objective-C class defined in MyClass.h as follows:
@interface MyClass : NSObject
-(instancetype)initWithA:(int)a andB:(int)b;
@end
A very simple class, with an init that takes two ints.
To access it from C++, you would do the following in your MyCppClass.hpp:
#include <objc/objc-runtime.h>
#ifdef __OBJC__
#define OBJC_CLASS(name) @class name // if imported in ObjC it knows it is a class
#else
#define OBJC_CLASS(name) typedef struct objc_object name // C++ will treat it as a struct, which is what an ObjC class is internally
#endif
OBJC_CLASS(MyClass);
namespace MyWrapper {
class MyCppClass {
MyClass* myObj;
public:
MyCppClass(int a, int b);
~MyCppClass();
};
}
If your C++ code will call ObjC classes/methods then the ObjC runtime has to be available. The macros allow forward declaration of ObjC classes in C++ code, and it will compile and run just fine. C++ will not complain. Just include MyCppClass.hpp in your C++ file, and use it like any C++ class.
Now the last step is in your MyCppClass.mm, which is an Objective-C++ file define as follows:
#include "MyCppClass.hpp"
#import "MyClass.h" // this is your ObjC class, imported here because you can't import it in C++ header
namespace MyWrapper {
MyCppClass::MyCppClass(int a, int b) :
myObj([[MyClass alloc] initWithA:a andB:b]) { }
MyCppClass::~ MyCppClass() {
[myObj release];
}
One final note, MyCppClass.mm needs to be compiled with compile with -fno-objc-arc flag