1

I would like to know how to properly navigate in an application using a NavigationController, to not instantiate a ViewController each time I call it for example:

In all know applications such as Instagram, when you click on a Toolbar Item, you access a viewController, but the state of this one is saved, if you were on a photo, it still is on this photo after you went to settings, post photo etc. And in my application, my NavigationController instantiate a new ViewController each time I want to access it, and it is time Consuming when you load data in ViewDidLoad for example.

Is there someone who could help me please ?

Benobab
  • 428
  • 1
  • 6
  • 25

1 Answers1

1

If you do not want to create a new controller - do not create it!

Create your controllers once and then reuse them. For example you can declare your controllers as a singletons:

let vc1 = MyViewController1()
let vc2 = MyViewController1()
let vc3 = MyViewController1()

And when you need to push some controller do not create a new one but reuse already created:

navigationVC.pushViewController(vc2, animated: true)

UINavigationController will throw an error if you will try to push a controller which is already in a navigation stack. So you will have to remove it from the navigation stack first:

// vc2 - is a controller that could be in the navigation stack and should be pushed once more
var controllers = navigationVC.viewControllers
if let index = controllers.indexOf(vc2){
    controllers.removeAtIndex(index)
}
navigationVC.setViewControllers(controllers, animated: false)

then you can push vc2 as usual. If it is possible in your app you should also check a case if vc2 should be pushed right after vc2.

Avt
  • 16,927
  • 4
  • 52
  • 72
  • In this case I have this error : Pushing the same view controller instance more than once is not supported – Benobab Sep 11 '15 at 11:02
  • Do you want to have few the same controllers in a navigation stack? – Avt Sep 11 '15 at 11:08
  • I want to call my existing viewController again and again, to save the state of this one, in in one of them I was completing a fields, I want this field with what I wrote inside, the next time I call it, is it possible ? – Benobab Sep 11 '15 at 11:34
  • ok. Do you want to be able to go back (via " – Avt Sep 11 '15 at 12:02
  • Not for these, because I'm already hiding the back button for those ones – Benobab Sep 11 '15 at 12:03
  • ok, now it is clear. I have updated the answer, please check. – Avt Sep 11 '15 at 12:18
  • All I have is Black screens rather than my ViewControllers. – Benobab Sep 11 '15 at 12:57