Search code examples
iosswiftobserversuserdefaults

Trying to remove an unregistered UserDefaults observer Swift


I'm new to Swift and iOS programming, so excuse my lack of knowledge...

I have a TabBar controller and one of the tabs' view controller registers an observer in its viewDidLoad() method like this:

UserDefaults.standard.addObserver(self, forKeyPath: "interests", options: .new, context: nil)

I am trying to remove the observer in the deinit() method like this:

UserDefaults.standard.removeObserver(self, forKeyPath: "interests")

However, unless I have gone into that tab before, I get this error: Cannot remove an observer for the key path "interests" because it is not registered as an observer.

I understand that if I don't go into the tab viewDidLoad() won't be called but I don't know a better place to add the observer. I don't get this error if I have gone into this view controller. Can you tell me if there is a better place to do that or if I'm doing something else wrong? Thank you.

EDIT Here is my full view controller

class InterestsViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        UserDefaults.standard.addObserver(self, forKeyPath: "interests", options: .new, context: nil)
    }

    deinit {
        UserDefaults.standard.removeObserver(self, forKeyPath: "interests")
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        // updating the UI
    }
}

Solution

  • From the docs:

    https://developer.apple.com/documentation/foundation/notificationcenter/1413994-removeobserver

    If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.

    if your app targets below iOS 9.0 then you can call the register/unregister on viewWillAppear and viewWillDisappear