0

How do you convert this to a weak reference to self?

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.handleMessage(_:)), name: "NewMessage", object: nil)

NSNotificationCenter.defaultCenter().removeObserver(self, name: "NewMessage", object: nil)

Also, a related question--when does the view controller actually get destroyed? I'm assuming when you tab in and out of different views, view controllers still stay alive right? i.e. They don't get destroyed on viewDidDisappear.

Prabhu
  • 12,995
  • 33
  • 127
  • 210
  • 1
    As of iOS 9, the notification center holds *weak* references to the observer, see for example http://stackoverflow.com/questions/39663984/why-do-you-have-to-remove-observer-in-ios8. – Martin R Dec 16 '16 at 17:16
  • Ok, so the notification center's reference to self will never be the cause of a view controller to stick around, right? – Prabhu Dec 16 '16 at 17:18
  • Correct. To clarify, before iOS 9 it stored an `assign` reference to the observer so it also didn't keep the observer in memory. It being an `assign` reference meant you had to remove yourself as an observer in `dealloc`/`deinit` or else your app would crash when it tried calling a selector on an object that had been deallocated. – AdamPro13 Dec 16 '16 at 18:11

1 Answers1

0

this is the function in viewcontroller where it actually get out of the momory so here you can remove observer

                deinit {
                    // you code

                }

and for making weak reference of self you can use

                weak var this = self