I have a navigation controller with 4 VCs pushed into it. I have a singleton class with a delegate property that is set to the VC which is on top of the stack. I am setting this delegate to nil in the dealloc method of each VC. I am setting the delegate in the viewdidappear method of the rootVC.
When I pop back to root VC from the 4th VC, the sequence of calling the dealloc methods (of all the VCs in stack) and viewdidappear method is following:
"FirstVC dealloc called"
"SecondVC dealloc called"
"viewdidappear of root VC is called"
"ThirdVC dealloc called"
Now, the issue I am facing is that the delegate gets set to nil even though I am setting it to self in the root VC's viewdidappear method (which is visible from the control flow too). How can I prevent this situation? I want the viewdidappear method to get called once all the VCs are really deallocated.
Thanks, Obaid
Since you can't predict the order of method calls unless Apple publishes some guarantee of what they are, perhaps you could program the singleton to be defensive by creating a method such as:
If the delegate matches the specified old delegate, set it to nil.
dealloc
is called automatically once a object is no longer needed. When you pop theThirdVC
, since the delegate property is still retaining it,dealloc
doesn't get called. Then, when your rootVC'sviewDidAppear
gets called, it sets therootVC
as the delegate. At this momment, your thirdVC is no longer needed, which triggers thedealloc
.One thing you could do is set the delegate property to nil not on dealloc, but on the
viewWillDisappear
method of eachViewController
, since this method will surely get called before the nextViewController
appears.