I'm trying to call a function after the user defaults change. Below is the code I'm using.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Watch user default changes
UserDefaults.standard.addObserver(self, forKeyPath: "arrayA", options: NSKeyValueObservingOptions.new, context: nil)
UserDefaults.standard.addObserver(self, forKeyPath: "arrayB", options: NSKeyValueObservingOptions.new, context: nil)
}
func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutableRawPointer) {
filterItems()
self.tableView.reloadData()
}
deinit {
UserDefaults.standard.removeObserver(self, forKeyPath: "arrayA")
UserDefaults.standard.removeObserver(self, forKeyPath: "arrayB")
}
The code was inspired from this answer. I have modified it a bit for Swift 3.
When doing an action that would update the user defaults the app crashes and the following is printed to the console.
An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Basically when the key arrayA
or arrayB
are changed I want it to call filterItems()
and self.tableView.reloadData()
. It could also call those on any user defaults change but that would be less efficient.