Sunday, April 8, 2012

iPhone - when is dealloc for a viewcontroller called?

I am using UINavigationController to move between views. When I move back and forth in views, the memory used by my app keeps on increasing. On placing NSLog statements in the dealloc method of all viewcontrollers, I noticed it was being called for only some viewcontrollers and not all that were popped.

For instance, this is the sequence in which views are pushed MainViewController -> viewcontroller1 -> viewcontroller2 -> viewcontroller3

Now in viewcontroller3 if I do a popToViewController:mainController, dealloc is called only for viewcontroller3. It is not called for viewcontroller1 and 2.

Can someone please tell me why this is happening.

Found the problem. The dealloc method was not being called if any of the references held by a viewcontroller were still in memory. In my case it was the MPMoviePlayerController object which was not released in viewcontroller1 and viewcontroller2.

Source: Tips4all


  1. It is a case of last on, first off. So if you imagine your first view controller is the bottom bun of a burger, you then add the burger (second view controller) and then the top burger (third view controller).

    If you go back to the burger you take off the top bun (popViewController: calls the dealloc method of the view that is popped). If you want to go back to the bottom bun then you have to pop the burger (dealloc is called every time the view is popped).

    not sure why on pop to root the second view controller's dealloc wouldn't be called though..


  2. where you navigate your controllers there should be need to write this line after pushviewcontroller,
    [viewControllername release];
    then it would be call each viewcontroller Dealloc method :)

  3. You should also keep in mind that dealloc is not always guaranteed to run.

  4. navigationController popToRootViewControllerAnimated:YES];
    It worked for me... calls all dealloc methos of my 10 view controllers