UIViewController -dealloc method not called

流过昼夜 提交于 2019-11-30 14:43:06

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;

If you haven't created any property to point to vc1, then it will be deallocated after making this switch.

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;
}

To get a print when the View Controller is deallocated you can implement the dealloc method as

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

Then to get a print when the View Controller left the view you can implement

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    NSLog(@"The instance of MyViewController left the main view")
}

If you use -presentViewController:animated:completion: you are retaining the parentViewController every time you call this method. ModalViewControllers are simply pushed on top of the other ViewController.

ModalViewControllers are only designed for some kind of information / User Input and stuff like that. If you want to dealloc the ParentViewController you have to deal with your own implementation.

dealloc method isn't called when the class is retained (or something in this class is retained) and not reeleased. It is justly for projects with both ARC and without it. So check your code twice.

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