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):
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.