我正在为要在 Objective-C 项目中使用的外部静态 C++ 库实现回调例程。现在我无法在回调和正常例程之间移动数据。正如您在下面看到的,我的“msgStore”被定义为 MyMessage 类的一部分,并且可以在类例程(例如 init())中使用。然而,从回调例程(它不是 MyMessage 类的一部分) 尝试相同操作失败。
@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];
}
最后一行代码给出了错误消息'msgStore' was not declared in this scope。我猜这是因为 aCBack 是一个普通的 C 函数,因此没有自动的“ self ”指针?
关于如何保存在回调中接收的数据以便在 Obj-C 类中使用的任何想法?
最佳答案
您不能从函数中调用 msgStore
,因为它不在函数的范围内。
有几种方法可以在函数中访问它。
一种是使用单例类。如果您计划只使用一个消息存储,那么您可以将该类设为单例。这意味着您可以通过调用类方法来获取该类的对象实例,您可以从任何范围执行此操作。另请参阅:What should my Objective-C singleton look like?
MyMessage * myMsg = [MyMessage sharedMessage]; // this will get you a pointer to the shared instance
另一种方法是,如果回调函数允许,您也可以将其作为 void * data
参数传递,然后将其转换为函数中的 MyMessage
。另请参阅 Alex Deem 的回答。
附言。您使用 [NSArray arrayWithCapacity:]
创建数组,您可能希望将其设为 [[NSArray arrayWithCapacity:] retain]
或只是 [[NSArray alloc] initWithCapacity :]
,因此该对象不会在下一轮自动释放池内务处理中消失。
关于c++ - 未在此范围内声明 msgStore (XCode),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1839093/