poptorootviewcontroller not calling dealloc method

2019-08-15 06:41发布

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

2条回答
Rolldiameter
2楼-- · 2019-08-15 07:00

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:

- (void)removeDelegate:(UIViewController *)oldDelegate;

If the delegate matches the specified old delegate, set it to nil.

查看更多
三岁会撩人
3楼-- · 2019-08-15 07:02

dealloc is called automatically once a object is no longer needed. When you pop the ThirdVC, since the delegate property is still retaining it, dealloc doesn't get called. Then, when your rootVC's viewDidAppear gets called, it sets the rootVC as the delegate. At this momment, your thirdVC is no longer needed, which triggers the dealloc.

One thing you could do is set the delegate property to nil not on dealloc, but on the viewWillDisappear method of each ViewController, since this method will surely get called before the next ViewController appears.

查看更多
登录 后发表回答