从 NSNotification 中删除 C++ 观察者?

Remove a C++ observer from NSNotification?

在C++中,为通知添加一个Observer并不难。但问题是我怎么能删除一个观察者。

[[NSNotificationCenter defaultCenter] addObserverForName:@"SENTENCE_FOUND" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {

所以通常我们使用

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"SENTENCE_FOUND" object:nil];

删除观察者。

但是因为 C++ 没有 self 而当我使用 this 时,我得到了以下错误

Cannot initialize a parameter of type 'id _Nonnull' with an rvalue of type 'DialogSystem *'

那么我怎样才能删除 C++ class 观察器呢?还是不可能?

-[NSNotificationCenter addObserverForName:object:queue:usingBlock:]documentation 复制:

Return Value

An opaque object to act as the observer.

Discussion

If a given notification triggers more than one observer block, the blocks may all be executed concurrently with respect to one another (but on their given queue or on the current thread).

The following example shows how you can register to receive locale change notifications.

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
self.localeChangeObserver = [center addObserverForName:NSCurrentLocaleDidChangeNotification object:nil
    queue:mainQueue usingBlock:^(NSNotification *note) { 
        NSLog(@"The user's locale changed to: %@", [[NSLocale currentLocale] localeIdentifier]);
    }];

To unregister observations, you pass the object returned by this method to removeObserver:. You must invoke removeObserver: or removeObserver:name:object: before any object specified by addObserverForName:object:queue:usingBlock: is deallocated.

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self.localeChangeObserver];

编辑: 从同一页面复制:

Another common pattern is to create a one-time notification by removing the observer from within the observation block, as in the following example.

NSNotificationCenter * __weak center = [NSNotificationCenter defaultCenter];
id __block token = [center addObserverForName:@"OneTimeNotification"
                                       object:nil
                                        queue:[NSOperationQueue mainQueue]
                                   usingBlock:^(NSNotification *note) {
                                       NSLog(@"Received the notification!");
                                       [center removeObserver:token];
                                   }];