移除后会发现通知

时间:2017-10-23 09:35:37

标签: ios swift notifications nsnotificationcenter

我正在viewDidAppear注册通知并在viewDidDisappear中将其删除。但即使在移除后它仍被观察到,我无法理解为什么。这是我的代码

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    NotificationCenter.default.addObserver(forName:Notification.Name(rawValue: kCustomNotification), object:nil, queue:nil) { notification in
        // my code
    }
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.removeObserver(kCustomNotification)
    NotificationCenter.default.removeObserver(self)
}

现在我使用push打开viewController屏幕,然后返回上一个控制器,但仍然会观察到此通知。

3 个答案:

答案 0 :(得分:0)

你应该删除观察者名称" kCustomNotification"与你添加它的方式相同

override func viewDidDisappear(_ animated: Bool) { 

  super.viewDidDisappear(animated) 

  NotificationCenter.default.removeObserver(self, name: 
  Notification.Name(rawValue: kCustomNotification), object: nil) 

}

答案 1 :(得分:0)

您使用addObserver:usingBlock方法:

func addObserver(forName name: NSNotification.Name?, 
          object obj: Any?, 
           queue: OperationQueue?, 
           using block: @escaping (Notification) -> Void) -> NSObjectProtocol

要取消订阅通知,您应该save returned object并使用它取消订阅:

override func viewDidAppear(_ animated: Bool) {
  super.viewDidAppear(animated)
   <...>
   if let observer = _observer
   {
      <unsubscribe>
   }
   _observer =  NotificationCenter.default.addObserver(<...>)
   <...>
 }


  override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    if let observer = _observer
    { 
       NotificationCenter.default.removeObserver(observer)
    }
} 

您可以在documentation

的讨论部分找到更多示例
  

要取消注册观察,您将传递此返回的对象   removeObserver( :)的方法。您必须调用removeObserver( :)或   removeObserver(_:name:object :)在指定的任何对象之前   addObserver(forName:object:queue:using :)已取消分配。

答案 2 :(得分:0)

如果在viewWillApper中添加观察者怎么办?