If the above answers did not help then check if your code is using KVO in the class where you receive this error. When KVO is sending a message to your observing class about a value on a key changing, if the class has been released by ARC then KVO will be trying to alert a non-existent address in memory about that changes, causing your app to throw this error.
Consider this, a class called MyViewController
and you want to observe when the bounds
property of it's view.layer
changes indicating a layout change from landscape to portrait. So you add the line:
// self is MyViewController
self.view.layer.addObserver(self, forKeyPath: "bounds", options: .new, context: nil)
This will alert your class if the view
size changed.
But if your viewController is dismissed, say a UINavigationController
pops it off the stack, KVO is still going to try and alert MyViewController
the view's bounds has changed (because now it's gone). Then when KVO does this your application is going to crash. In your debug console you would see the following message:
-[MyViewController retain]: message sent to deallocated instance
This is because you must remove the observer (MyViewController
) for that keyPath. It is best to do this before MyViewController
is dismissed, ike so:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.view.layer.removeObserver(self, forKeyPath: "bounds")
}
Now when you attempt to pop MyViewController
from the navigation stack there will be no error.