Search code examples
iosdelegatesdeallocstrong-references

iOS : dealloc is not getting called if strong delegate set to self


Say, I've a class (say "MyClass") of type UIView where I declared, a property of type (nonatomic, strong) for class delegate, to handle events will fire by the class.

Application is ARC enabled, and it's working just fine, a time I found something interesting, I put a dealloc in one of my view controller (Say TempViewController), where I am setting delegate of MyClass to self. Whenever I pop from TempViewController, it should call its dealloc method, but it isn't. I don't know why but its not, I put deallocs for other classes, and they all getting called.

Then I found that, its not calling in TempViewController because I've set MyClass delegate. I test the same with other classes too, and then it stops calling dealloc.

Later I change, delegate property to, assign instead of strong, though its working fine again.

One other solution I found is, by setting nil in viewDidDisappear for the delegate of MyClass (like we did for MKMapView or UIWebView), it'll call dealloc for the same TempViewController class.

What's causing the problem? Any help, suggestion?


Solution

  • If you give strong property to your delegate, it will increase retain count. When you pop from navigation queue, it also just decrease retain count. So even-though you pop your view controller, it have retain count via delegate(if strong). Your dealloc only gets call when retain count is 0

    Notes: When you set nil to delegate in Disappear, your assigned delegate decrease retain count via setter method and assign nil to delegate. That's why, it get call when set nil.

    So you can declare you delegate as weak as like

    @property (nonatomic, weak) id<Protocol> delegate;