I’m learning about UINavigationController and UIViewControllers. Here is the simple app I build. Notice that I use ARC.
My app have a navigation controller and two view controllers (let’s call them FirstViewController and SecondViewController). When the app is launched navigation controller push the FirstViewController on the stack.
In FirstViewController I have a button which push the SecondViewController when is touched. Here is some code.
FirstViewController.m
-(IBAction)pushSecondViewController
{
SecondViewController *secondViewController = [SecondViewController alloc]init];
[self.navigationController pushViewController:secondViewController animated:YES];
}
In the second view controller I have a button which pop the current view controller from the stack.
SecondViewController.m
-(IBAction)popViewController
{
[self.navigationController popViewControllerAnimated:YES];
}
So far, so good. Here are my questions:
Does the navigationController check for an existing instance of SecondNavigationController and if such not exist then it creates a new one?
If not, should I use singleton to make sure that only one instance is created and reused instead of creating a new instance every time when the button which push the SeconViewController is touched?
With your current code, the second view controller will be destroyed when it is popped from the stack, so no, the navigation controller won’t re-use it.
If you really want to keep the second view controller around, make it a strong property of the first view controller, but don’t do this unless you actually have a reason to – the method you are using is standard and creating a new view controller is generally preferred to taking up lots of memory with view controllers that aren’t even on screen. Memory is more scarce than processor resource, creating view controllers happens all the time.