0
votes

I have 2 ViewControllers VCA and VCB. I have an observer in VCA set up in viewDidAppear

I navigate from VCA to VCB and then when you press a button on VCB the notification is posted which performs some function then I dismiss VCB and VCA appears again


//VCB 

    @IBAction func buttonPressed(_ sender: Any) {
        NotificationCenter.default.post(name:    Notification.Name("name"), object: nil)
}

 @IBAction func backButtonPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }

//VCA

 override func viewDidAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(self.someFunction), name: Notification.Name("name"), object: nil)
}

Now the problem is as soon as VCA appears it adds another observer I get that the problem is I need to remove the Observer but if I remove it in viewWillDisappear , the notification never get called because it is removed before I can post it

I tried to remove the observer in VCB like so

    @IBAction func backButtonPressed(_ sender: Any) {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "VCA") as! VCA
        NotificationCenter.default.removeObserver(vc, name: Notification.Name("stateChange"), object: nil)
        dismiss(animated: true, completion: nil)
    }

But that didn't work

So I need to remove observer in VCA from VCB when dismissing VCB. I have looked at Remove notification observer from another view controller already

But it is in OBJC and I didn't understand it exactly , plus the OP hasn't marked it as correct solution or commented that it did work

1
Add the observer in 'viewDidLoad` - Paulw11

1 Answers

0
votes

First it's better here to set a delegate instead of notification center as the latter is used for 1-M not 1-1 notify

Second You can add the observer inside viewDidLoad

if you need to remove it after dismiss of vcB then end of the function someFunction do

 NotificationCenter.default.removeObserver(self)