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

2k views Asked by At

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?

3

There are 3 answers

0
Mani On BEST ANSWER

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;
0
Midhun MP On

It is because you declared the property as strong, change it to weak.

@property (nonatomic, weak) id<yourprotocol> delegate;
0
Joshua On

It also means that you are still holding or referring to a property of Another class and the compiler can't call the dealloc method for that class. its either you set it to nil if your done or assign a weak reference to it. try to read this answer as well