0

I am working with UINavigationController. I want to prevent to create multiple instances from same type ViewController. If I have a UINavigationController with four children ViewController(s) (A, B, C, D) and another ViewController (E) and I navigate from A -> B -> C -> D and in DViewController I will instantiate EViewController and I will present it .. and from EViewController I go to A ViewController I will have 2 instances from AViewController .. and I want to prevent it.

Here is storyboard with all ViewController(s): enter image description here

How I navigate from D to E:

let vc = self.storyboard?.instantiateViewController(withIdentifier: "E") as? E   
self.present(vc!, animated: true)

How I navigate from E to A:

self.performSegue(withIdentifier: "aSegue", sender: nil)

I found some solutions as:

1) When I am in E ViewController should destory all ViewController(s) (A, B, C, D)

2) When I navigate from E to A .. check if exists AViewController .. if it exists set as rootViewController, else create it and present it:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
var aVC: AViewController?
if let viewControllers = appDelegate.window?.rootViewController?.childViewControllers {
  for vc in viewControllers {
    print(vc.debugDescription)
    if vc.isKind(of: AViewController.self) {
      aVC = vc as! AViewController
      break
    }
  }
}


if let vc = aVC {
  let navigation = UINavigationController(rootViewController: vc)
  AppDelegate.delegate().setRootViewController(view: navigation)
} else {
    let vc = self.storyboard?.instantiateViewController(withIdentifier: "AViewController") as? AViewController
    self.present(vc!, animated: true)
}

3) Create singleton manager for each ViewController (example: link)

class AManager {
     static let sharedInstance = AManager()
}

Hope you understand my problem. Looking for a good solution. Thanks in Advance.

badhanganesh
  • 3,427
  • 3
  • 18
  • 39
Andrei Lupu
  • 154
  • 1
  • 7
  • 1
    Use an unwind segue to `A` from `E` or simply use `navigationController?.popToRootViewController(animated: true)` – Mukesh May 02 '18 at 08:44
  • @Mukesh you are right. I resolved my problem using with unwind .. I thought unwind is used only when current viewcontroller is in same NavigationController as destinatination viewcontroller. In my situation E ViewController is an independent viewcontroller and (A, B, C, D) are in same NavigationController. You saved my day! Thank you very much – Andrei Lupu May 02 '18 at 09:24
  • Glad it worked. Enjoy. – Mukesh May 02 '18 at 09:26

0 Answers0