I have an objective C class. In it, I created a init method and set up a NSNotification in it
//Set up NSNotification
[[NSNotificationCenter defaultCenter] a
In general I put it into the dealloc
method.
SWIFT 3
There are two cases of using notifications: - they are needed only when the view controller is on screen; - they are needed always, even if user opened another screen over current.
For the first case the correct place to add and remove observer are:
/// Add observers
///
/// - Parameter animated: the animation flag
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(...)
}
/// Remove observers
///
/// - Parameter animated: the animation flag
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
for the second case the correct way is:
/// Add observers
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(...)
}
/// Remove observers
///
/// - Parameter animated: the animation flag
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if self.isBeingDismissed // remove only when view controller is removed disappear forever
|| !(self.navigationController?.viewControllers.contains(self) ?? true) {
NotificationCenter.default.removeObserver(self)
}
}
And never put removeObserver
in deinit{ ... }
- it's a MISTAKE!