Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How UINavigationController and UIViewController works?

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?

like image 689
ihodo Avatar asked Mar 11 '12 15:03

ihodo


2 Answers

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.

like image 97
jrturton Avatar answered Oct 08 '22 01:10

jrturton


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.

like image 31
Lorenzo B Avatar answered Oct 07 '22 23:10

Lorenzo B