I have a UIView similar to the one you see below:
class ViewTaskViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { override func viewDidLoad() { super.viewDidLoad() subscribeToNotifications() } func subscribeToNotifications() { let notification = NotificationCenter.default notification.addObserver(forName: Notification.Name(rawValue: "TimerUpdated"), object: nil, queue: nil, using: handleUpdateTimer) print("Subscribed to NotificationCenter in ViewTaskViewController") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("TUFU TUFU TUFU") NotificationCenter.default.removeObserver(self) } deinit { print("DENINT") } @objc func handleUpdateTimer(notification: Notification) { if let userInfo = notification.userInfo, let timeInSeconds = userInfo["timeInSeconds"] as? Int { withUnsafePointer(to: &self.view) { print("We got timeeeeee \(timeInSeconds) \($0)") }
}
The problem I am facing is that I cannot remove observers from this particular UIView when the user clicks the back button and returns to another viewController.
ViewWillDisppear , but deinit not called. It is strange that if we remove subscribeToNotifications() from viewDidLoad() , then deinit is called.
Another problem is memory leak. As you can see in the screenshot below, when the view subscribes to notifications, and the user leaves / returns to the view, memory usage increases. 
Now compare this to the fact that when subscribeToNotifications() commented out, the increase in memory usage and only one instance of viewController does not increase.
The conclusion is that there seems to be a correlation between creating a subscription to notify a new instance of UIView, so deinit not called.
I would like to know if there is a way to de-initialize the submission and unsubscribe from the notification.
Please let me know if you need more information. :)
ios memory-leaks swift nsnotification deinit
Sohil pandya
source share