How does UINavigationController and UIViewController work?

I will learn about UINavigationController and UIViewController s. Here is a simple application that I am creating. Please note that I am using ARC.

My application has a navigation controller and two view controllers (call them FirstViewController and SecondViewController ). When the application starts, the navigation controller pushes FirstViewController onto the stack.

In FirstViewController I have a button that clicks SecondViewController when touched. Here is the 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 that pops the current view controller from the stack.

SecondViewController.m

 -(IBAction)popViewController { [self.navigationController popViewControllerAnimated:YES]; } 

So far so good. Here are my questions:

Does navController check an existing SecondNavigationController instance, and if one does not exist, does it create a new one?

If not, should singleton be used to ensure that only one instance is created and reused instead of creating a new instance each time the button that clicks the SeconViewController ?

+6
source share
2 answers

With your current code, the second controller will be destroyed when it pops out of the stack, so no, the navigation controller will not reuse it.

If you really want to save the second view controller, make it a strong property of the first view controller, but do not do it if you really have no reason - the method you use is standard and creates a new view controller, usually prefers to occupy a lot of memory with view controllers, which do not even appear on the screen. Memory is scarce than a processor resource, so the creation of view controllers occurs all the time.

+4
source

I agree with jrturton and add the following recommendations.

Firstly, in my opinion, it is not recommended to create controllers as single ones.

Then you need to check yourself if an instance of some type exists in the controller array UINavigationController .

 @property(nonatomic, copy) NSArray *viewControllers 

Finally, you can create a strong link for your controller, but this is not necessary. Creating a new controller is very fast. Instead of having a strong link to it, I will cache the data presented on it, if any. This will allow the user to wait for already downloaded data.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/910445/


All Articles