【发布时间】:2009-12-03 10:37:15
【问题描述】:
我正在为要在 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' is not declared in this scope。我猜这是因为 aCBack 是一个普通的 C 函数,因此没有自动“自我”指针?
任何想法如何保存在回调中接收到的数据以便在 Obj-C 类中使用?
【问题讨论】:
-
我可以在回调中做 Obj-C 的东西,所以我能以某种方式创建或请求 MyMessage 对象指针吗?不是创建新对象,而是指向已经存在的对象?好吧,我猜一种解决方案可能是将 msgStore 创建为单例。希望会有更简单的事情......
标签: c++ objective-c scope callback