2

Maybe the title does not provide a good description so please read the following.

I have a notification that is set to listen to an event:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.checkIfNotificationsWereTurnedOnAfterAlertShowing), name: UIApplicationWillEnterForegroundNotification, object: UIApplication.sharedApplication())

Then I want to remove observer on this notification. I found that I need to use deinit like this:

deinit  { 
    NSNotificationCenter.defaultCenter().removeObserver(UIApplicationWillEnterForegroundNotification)
    print("deinit")
}

But the problem is that when i close the view controller, the program never executes deinit function. In this answer i found that it could be due to strong reference.

I checked many links but was not able to find how to declare a weak reference for a notification. So how can I declare a weak notification?

Hope my question is clear.

Looking forward for your help.

Community
  • 1
  • 1
Tung Fam
  • 7,899
  • 4
  • 56
  • 63
  • 2
    related: http://stackoverflow.com/questions/425354/what-type-of-reference-does-nsnotificationcenter-keep-for-observers-object – Wain Aug 08 '16 at 13:29
  • It is weak reference. You must have something else hanging on to it. – Rob Aug 08 '16 at 14:02
  • Refer this: http://stackoverflow.com/questions/26971415/deinit-never-called – Santosh Aug 08 '16 at 14:13
  • 2
    As a rule, view controllers should add observations in `viewWillAppear` or `viewDidAppear` and remove them in `viewWillDisappear` or `viewDidDisappear`. This will address almost all life-cycle issues. It is somewhat normal for view controllers to continue to exist after being taken off screen (depending on how they were displayed); however they should never be observing notifications when they are offscreen. – Rob Napier Aug 08 '16 at 14:27

1 Answers1

2

I was not able to find the way to handle this with deinit so I decided to remove observer in viewWillDisappear which worked well for me. Suggested by Rob Napier in the comment above

Community
  • 1
  • 1
Tung Fam
  • 7,899
  • 4
  • 56
  • 63