8

我有一个 C++ 类,我最近从 *.cpp 重命名为 *.mm 以支持 Objective-c。所以我可以添加以下objective-c代码。

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notificationHandler:) 
                                                 name:@"notify"
                                               object:nil];
  • 如何/我可以在 C++ 中编写 notificationHandler 方法吗?
  • 设置 addObserver:self 属性会起作用吗?
4

3 回答 3

18

或者您也可以只使用块并执行以下操作:

[
    [NSNotificationCenter defaultCenter] addObserverForName: @"notify"
    object: nil
    queue: nil
    usingBlock: ^ (NSNotification * note) {
        // do stuff here, like calling a C++ method
    }
];
于 2014-09-18T01:20:08.187 回答
16

您需要一个 Objective-C 类来处理 Objective-C 通知。核心基金会来救援!

在.. 任何你开始监听通知的地方,例如你的构造函数:

static void notificationHandler(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo);

MyClass::MyClass() : {
    // do other setup ...

    CFNotificationCenterAddObserver
    (
        CFNotificationCenterGetLocalCenter(),
        this,
        &notificationHandler,
        CFSTR("notify"),
        NULL,
        CFNotificationSuspensionBehaviorDeliverImmediately
    );
}

完成后,例如在您的析构函数中:

MyClass::~MyClass() {
    CFNotificationCenterRemoveEveryObserver
    (
        CFNotificationCenterGetLocalCenter(),
        this
    );
}

最后,一个处理调度的静态函数:

static void notificationHandler(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    (static_cast<MyClass *>(observer))->reallyHandleTheNotification();
}

达达!

于 2011-05-19T17:24:43.987 回答
4

由于 Objective-C 方法与 C++ 相比,Objective-C 方法如何处理方法调用,因此您不能将 C++ 方法添加为观察者。您必须有一个 Objective-C 类(用@interface Class..声明@end)来响应这些方法。

您唯一的选择是将您的 C++ 类包装在一个 Objective-C 类中,或者只使用一个非常轻量级的包装器,它只包含一个对象的引用,并在通知到达后静态调用一个方法。

于 2011-05-19T17:17:50.977 回答