I’m implementing callback routines for external static C++ library to be used in Objective-C project. Now I have trouble moving data between callback and normal routines. As you can see below my “msgStore” is defined as part of MyMessage class and can be used within class routines such as init(). However attempting same from callback routine, which is NOT part of the MyMessage class, fails.
@interface MyMessage : NSObject {
NSMutableArray *msgStore;
}
@property (nonatomic, retain) IBOutlet NSMutableArray *msgStore;
// Callback functions declarations
void aCBack (const std::string text);
@implementation MyMessage
@synthesize msgStore;
- (id)init
{
if ((self = [super init])) { }
if (msgStore == nil) {
msgStore = [NSMutableArray arrayWithCapacity:100];
}
return self;
}
void aCBack (const std::string text)
{
NSString *msg = [[NSString alloc] initWithCString:(const char *)text.c_str() encoding:NSUTF8StringEncoding];
[msgStore insertObject:msg atIndex:0];
}
The last code line gives error message ‘msgStore’ was not declared in this scope. I’m guessing it’s because aCBack is a plain C function and thus does not have automatic “self” pointer?
Any ideas how to save data received in callback for use inside Obj-C class?
You cannot call
msgStorefrom the function because it is not in the scope of the function.There are a few ways to get to it in the function.
One is to use a singleton class. If you plan on only using one message store, then you can make that class a singleton. That means you can get the object instance of that class by calling a class method, which you can do from any scope. See also: What should my Objective-C singleton look like?
Another way is, if the callback function allows, you can also pass it as a
void * dataargument, then cast it to aMyMessagein the function. See also Alex Deem’s answer.PS. You create the array with
[NSArray arrayWithCapacity:], which you might want to make[[NSArray arrayWithCapacity:] retain]or just[[NSArray alloc] initWithCapacity:], so the object won’t vannish on the next autoreleasepool housekeeping round.