I'm learning about UINavigationController
and UIViewController
s. 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.
I agree with jrturton and I add the following guidelines.
First, in my opinion it's not a good idea to make controllers as singletons.
Then, you have to check yourself if an instance of some type exists in the UINavigationController
"controllers array".
@property(nonatomic, copy) NSArray *viewControllers
Finally, you could create a strong reference for your controller but it's not necessary at all. The creation of a new controller it's very quickly. Instead of having a strong reference of it, I would cache data presented on it, if any. This to avoid the user to wait for already downloaded data.
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With