8

I have a view contoller (for log in) that defines deinit method to remove observers. When user taps on Register button, the controller calls performSegueWithIdentifier to load registration view controller. I defined deinit method to remove all observers. However, that method is not being called. I read it somewhere that it is because the viewcontroller is not being destroyed and the pointer to it is hold somewhere. Could anyone explain the reason behind this?

Thanks

EDIT : Although I agree that the link provided in the comment section holds the same question, there is no answer or clear answer to that. The highest upvoted reply suggested to define something inside deinit instead of leaving it blank. That does not answer the explination I'm looking for. For that reason, I'm keeping this question until somebody can point out my understanding is incorrect.And also, I do think that Matt explains it succinctly and clearly.

KMC
  • 1,677
  • 3
  • 26
  • 55
  • http://stackoverflow.com/a/33580360/1979882 – Vyacheslav Jan 20 '17 at 21:03
  • 1
    From Swift [documentation](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48): "... it is possible to write code in which an instance of a class _never_ gets to a point where it has zero strong references. This can happen if two class instances hold a strong reference to each other, such that each instance keeps the other alive. This is known as a _strong reference cycle_." – 0x416e746f6e Jan 20 '17 at 21:08
  • 1
    Possible duplicate of [Deinit never called](http://stackoverflow.com/questions/26971415/deinit-never-called) – 0x416e746f6e Jan 20 '17 at 21:09

1 Answers1

24

The usual reason for failure to trigger deinit when expected is that you have a retain cycle that prevents your view controller from going out of existence.

(Sometimes the reason is that your expectation that the view controller would be destroyed under the circumstances is incorrect. But assuming it is correct, a retain cycle is the reason.)

You mentioned removing all observers. What kind of observers? If we're talking about NSNotification, that is often how you get a retain cycle. The notification center retains the observer until you unregister it. You thus cannot get deinit until after the observer has been removed. Therefore, you cannot remove the observer in deinit.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • My book discusses the unusual memory management of notifications here: http://www.apeth.com/iOSBook/ch12.html#_unusual_memory_management_situations – matt Jan 20 '17 at 21:05
  • Yes, it is NSNotification and I'm trying to remove those observers from deinit. So my problem is....I'm removing observers from denint and denint will only be called when observers are removed. Thanks for the detailed explination and the link too! – KMC Jan 20 '17 at 21:15