Dealloc not called changing tab

自作多情 提交于 2019-12-13 05:08:56

问题


Let's suppose to have a tab bar controller with two tabs, A and B, where A is a navigation controller.

When the user is in A, he can push A1 and then A2, which are both view controllers. A back button on A2, performs:

[self.navigationController popViewControllerAnimated:YES];

which correctly triggers the dealloc method on A2.

If the user is in A2 and then switches to tab B, I need the dealloc method to be called on A2; therefore I've implemented the following method in the TabBarController:

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    UINavigationController *nc = (UINavigationController*)tabBarController.selectedViewController;
    [nc popToRootViewControllerAnimated:YES];

    return YES;
}

but in this flow the dealloc method of A2 is never called! How is it possible that popping from A2 to A1 it works, whereas changing tabs the view controller is not deallocated?

Thanks for any hint!

DAN


回答1:


dealloc is only for removing observers and freeing memory -- when or if it is called is up to the runtime

e.g.
think of the cases of release vs. autorelease (influence when it is called) or if you terminate an app (not called at all)

instead on relying on dealloc, write a method you explicitly call.. e.g. something like stop or finish or cleanup

or... use viewDidDisappear.

-- in any case, don't rely on dealloc




回答2:


It seems that didSelectViewController is triggered before the tab controller has switched to the destination tab. Therefore the execution of the method popToRootViewControllerAnimated correctly pops all the view controllers, but can't really release the visible one, as it is currently being depicted by the app.

To achieve my result, I've figured out the following solution. In the viewDidAppear method of all the view controllers which correspond to the first view controller for each tab, I execute popToRootViewControllerAnimated (all of them are navigation controller).



来源:https://stackoverflow.com/questions/18508425/dealloc-not-called-changing-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!