【问题标题】:Which is the better way to remove self from NSNotificationCenter? Just remove self or remove self from the specific notification name?从 NSNotificationCenter 中删除 self 的更好方法是什么?只是从特定的通知名称中删除 self 或删除 self ?
【发布时间】:2015-07-14 06:21:05
【问题描述】:

我只想知道:在 dealloc 方法中从 NSNotificationCenter 中删除 self 的更好方法是什么?或者是否有人在这两种方式之间遇到过不同的行为?

只需通过以下代码删除自我:

[[NSNotificationCenter defaultCenter] removeObserver:self];

或从特定通知名称中删除 self ,如下所示:

[[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName object:someObj];

PS.我刚刚发现一个奇怪的事情,当我通过第一种方式从通知中心删除 self 但被释放的对象仍然可以接收通知时,这当然会调用崩溃异常.

【问题讨论】:

    标签: ios objective-c notifications dealloc


    【解决方案1】:
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    

    这将删除观察者为self的所有注册

    UIViewController 可能有它自己不想在viewWillDisappear: 中删除的注册。不太可能使用addObserver:selector:name:object: 在公共 API 中注册任何通知,因为这会阻止您在 UIViewController 子类中注册它们,但它肯定可以在现在或将来的版本中注册非公共通知。

    一种安全的注销方式是每次注册发送一次removeObserver:name:object:

    - (void)deregisterForNotifications {
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center removeObserver:self name:someNotification object:nil];
    object:nil];
    }
    

    【讨论】:

      【解决方案2】:

      在dealloc中,更好用

      [[NSNotificationCenter defaultCenter] removeObserver:self];
      

      否则总是使用

      [[NSNotificationCenter defaultCenter] removeObserver:self name:NotificationName object:someObj];
      

      在 Xcode 中,将光标放在此方法上,然后在右侧面板上查看快速帮助。

      【讨论】:

      • 可以在 ViewDidAppear 中使用[[NSNotificationCenter defaultCenter] removeObserver:self]; 吗?
      • 不建议这样做。因为即使超类仍然需要它,它也会移除观察者。
      猜你喜欢
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多