How to add an observer to NSNotificationCenter in

2019-05-07 03:00发布

Hey guys I have a C++ class that I recently renamed from *.cpp to *.mm to support objective-c. So I can add the following objective-c code.

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notificationHandler:) 
                                                 name:@"notify"
                                               object:nil];
  • How do/Can I write the notificationHandler method in c++?
  • Will setting addObserver:self property work?

3条回答
smile是对你的礼貌
2楼-- · 2019-05-07 03:10

Or you could also just use blocks and do:

[
    [NSNotificationCenter defaultCenter] addObserverForName: @"notify"
    object: nil
    queue: nil
    usingBlock: ^ (NSNotification * note) {
        // do stuff here, like calling a C++ method
    }
];
查看更多
一纸荒年 Trace。
3楼-- · 2019-05-07 03:24

You'd need an Objective-C class to handle Objective-C notifications. Core Foundation to the rescue!

In.. wherever you start listening for notifications, e.g. your constructor:

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
    );
}

When done, e.g. in your destructor:

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

And finally, a static function to handle the dispatch:

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

Ta da!

查看更多
一纸荒年 Trace。
4楼-- · 2019-05-07 03:31

You can't add a C++ method as an observer because of how Objective-C method handles method invocation vs C++. You must have an Objective-C class (Declared with @interface Class .. @end) to respond to those methods.

Your only option is to wrap your C++ class in an Objective-C class, or just have a very light wrapper that just has a reference to an object and calls a method statically once the notification arrives.

查看更多
登录 后发表回答