UIViewController -dealloc 方法未调用 [英] UIViewController -dealloc method not called
问题描述
我正在使用自动引用计数.我有一个自定义的 UIViewController
子类,每当我调用 -presentViewController:animated:completion:
或从超级视图中删除它的视图时,我都希望 NSLog
像我被释放"这样的东西,所以我知道视图控制器已成功删除.我已经在我的视图控制器中实现了 -dealloc
方法.但是,我开始了一个测试项目,其中我只有两个 UIViewController
实例(没有保留循环)并且在我推送第二个 UIViewController
时也没有调用 -dealloc
code> 模态或当我删除超级视图或从父视图控制器中删除它时.我错过了什么吗?在我的原始项目(不是测试用例)中,Instruments 向我展示了这些控制器留下了我无法摆脱的内存占用.
I am working with Automatic Reference Counting.
I have a custom UIViewController
subclass and whenever I call -presentViewController: animated:completion:
or remove its view from the superview I would like to NSLog
something like "I am dealloced" so I know that the view controller has successfully been removed. I have implemented the -dealloc
method in my view controller. However I started a test project where I just had two UIViewController
instances (no retain cycles) and -dealloc
is not called either when I push the second UIViewController
modally or when I remove the superview or when I remove it from the parent view controller. Am I missing something ? In my original project (not the test case) Instruments shows me that those controllers leave a memory footprint that I can't get rid off.
推荐答案
如果您想切换视图控制器,并且要取消分配您要切换的视图控制器,那么只需切换窗口的根视图控制器即可.因此,如果您在 VC1 中并想转到 VC2,请在 VC1 中执行此操作:
If you want to switch view controllers, and have the one you're switching away from be deallocated, then just switch the root view controller of the window. So, if you're in VC1 and want to go to VC2, then do this in VC1:
VC2 *vc2 = [[VC2 alloc] init]; // or however else is appropriate to get an instance of this class
self.view.window.rootViewController = vc2;
如果您还没有创建任何属性来指向 vc1,那么在进行此切换后它将被释放.
If you haven't created any property to point to vc1, then it will be deallocated after making this switch.
如果你想使用模态展示或模态转场(在切换控制器时获得动画),你仍然可以通过viewDidAppear的viewDidAppear方法在展示后切换根视图控制器来释放初始控制器vc2:
If you want to use a modal presentation or a modal segue (to get the animation when you switch controllers), you can still get the initial controller to be deallocated by switching the root view controller after the presentation from the viewDidAppear method of vc2:
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.view.window.rootViewController = self;
}
这篇关于UIViewController -dealloc 方法未调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!