如何使用Objective-C++在C++类中向NSNotificationCenter添加观察者?

val*_*lmo 4 iphone objective-c++ nsnotificationcenter

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

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notificationHandler:) 
                                                 name:@"notify"
                                               object:nil];
Run Code Online (Sandbox Code Playgroud)
  • 如何/我可以在c ++中编写notificationHandler方法吗?
  • 设置addObserver:self属性是否有效?

Jon*_*pan 13

您需要一个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
    );
}
Run Code Online (Sandbox Code Playgroud)

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

MyClass::~MyClass() {
    CFNotificationCenterRemoveEveryObserver
    (
        CFNotificationCenterGetLocalCenter(),
        this
    );
}
Run Code Online (Sandbox Code Playgroud)

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

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

塔达!


小智 12

或者您也可以使用块并执行:

[
    [NSNotificationCenter defaultCenter] addObserverForName: @"notify"
    object: nil
    queue: nil
    usingBlock: ^ (NSNotification * note) {
        // do stuff here, like calling a C++ method
    }
];
Run Code Online (Sandbox Code Playgroud)