5

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.

4

4 回答 4

11

如果您想切换视图控制器,并让您要切换的视图控制器被释放,那么只需切换窗口的根视图控制器。所以,如果你在 VC1 并想去 VC2,那么在 VC1 中执行此操作:

VC2 *vc2 = [[VC2 alloc] init]; // or however else is appropriate to get an instance of this class
self.view.window.rootViewController = vc2;

如果您尚未创建任何指向 vc1 的属性,则在进行此切换后它将被释放。

如果您想使用模态演示或模态 segue(在切换控制器时获取动画),您仍然可以通过在演示后从 vc2 的 viewDidAppear 方法切换根视图控制器来释放初始控制器:

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.view.window.rootViewController = self;
}
于 2013-05-04T22:01:55.073 回答
0

当类被保留(或此类中的某些内容被保留)且未释放时,不会调用 dealloc 方法。它适用于有 ARC 和没有 ARC 的项目。所以检查你的代码两次。

于 2013-05-04T13:00:49.387 回答
0

如果您使用-presentViewController:animated:completion:,则每次调用此方法时都会保留 parentViewController。ModalViewController 被简单地推到另一个 ViewController 之上。

ModalViewControllers 只为某种信息/用户输入和类似的东西而设计。如果你想释放 ParentViewController 你必须处理你自己的实现。

于 2013-05-04T10:05:29.730 回答
0

要在视图控制器被释放时打印,您可以将 dealloc 方法实现为

- (void) dealloc {
    NSLog(@"The instance of MyViewController was deallocated");
}

然后在 View Controller 离开视图时打印,您可以实现

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    NSLog(@"The instance of MyViewController left the main view")
}
于 2013-05-04T09:50:45.780 回答