Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIViewController -dealloc method not called

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.

like image 883
the_critic Avatar asked May 04 '13 09:05

the_critic


1 Answers

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;
}
like image 88
rdelmar Avatar answered Nov 15 '22 03:11

rdelmar