0

in example : in A vc i added observer :

NotificationCenter.default.addObserver(self, selector: #selector(onDidReceive(_:)), name: .didReceive, object: nil)

can i remove observer in A vc when i am in B vc ?

i tried this (in B vc):

NotificationCenter.default.removeObserver(self)

but it didnt work

it's possibile to do ? or i must remove observer in same VC where i created ?

  • 1
    `self` in B _is_ B, so it can never remove A. You need to store your A vc instance somewhere, and call `.removeObserver(aInstance)` – Gereon Aug 28 '19 at 10:53
  • In BVC, `self` is not AVC instance. What about doing `addObserver()` in `viewDidAppear()`, and `removeObserver()` in `viewDidDisappear()`? – Larme Aug 28 '19 at 10:53
  • @Larme Maybe he doesn't want to remove observer in `AVC`'s `viewDidDisappear` and want to remove the observer from `BVC` after some action is performed – RajeshKumar R Aug 28 '19 at 10:56
  • @Gereon something like this (in B VC ): `let main = UIStoryboard(name: "A", bundle: nil) let viewcontroller = main.instantiateViewController(withIdentifier: "AVC") NotificationCenter.default.removeObserver(viewcontroller)` ? –  Aug 28 '19 at 10:58
  • @alexking No. You are creating new instance of `AVC`. You should get the exising instance of `AVC` – RajeshKumar R Aug 28 '19 at 10:59
  • @RajeshKumarR so i must create global var type of `ViewController` and in `AVC `must assign `global var (must be name) = self` and in `BVC` `NotificationCenter.default.removeObserver(global var (must be name))` ? –  Aug 28 '19 at 11:02

2 Answers2

0

You can get the instance of AVC from the navigation controller's view controllers property and remove the observer.

//BVC

if let vc = self.navigationController?.viewControllers.first(where: { $0 is AVC }) {
    NotificationCenter.default.removeObserver(vc)
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
0

just add a piece of line in the viewController where the observer was added

deinit {
    NotificationCenter.default.removeObserver(self)
}

this will remove the observer

Awais Mobeen
  • 733
  • 11
  • 19
  • https://stackoverflow.com/a/40339926/10687271 As of iOS 9 (and OS X 10.11), you don't need to remove observers yourself, if you're not using block based observers though. The system will do it for you, since it uses zeroing-weak references for observers, where it can. – Rey Bruno Aug 28 '19 at 14:06