代码之家  ›  专栏  ›  技术社区  ›  Patroclus

从NSn通报中删除C++观测器?

  •  0
  • Patroclus  · 技术社区  · 8 年前

    在C++中,为通知添加一个观测器并不困难。但问题是我怎么能去掉一个观察者。

    [[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++类观测器呢?还是不可能?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Willeke    8 年前

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

    返回值

    作为观察者的不透明物体。

    讨论

    如果给定的通知触发多个观察者块,则这些块可以彼此同时执行(但在它们的给定队列或当前线程上)。

    下面的示例演示如何注册以接收区域设置更改通知。

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

    若要注销观察,请将此方法返回的对象传递给removeObserver:。在释放addObserverForName:object:queue:usingBlock:指定的任何对象之前,必须调用removeObserver:或removeObserver:name:object:。

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

    编辑: 从同一页复制:

    另一个常见的模式是通过从观察块中移除观察者来创建一次性通知,如下例所示。

    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];
                                       }];
    
    推荐文章