I have a UINavigationController
with root HomeViewController(). HomeViewController has a property named someString. I want to access someString from another view controller that has been pushed onto the navigation stack programmatically:
navigationController?.pushViewController(DetailViewController(), animated: true)
In the DetailViewController that wants to access someString I am doing this:
var homeViewController: HomeViewController!
override func viewDidLoad() {
super.viewDidLoad()
let navController = self.navigationController!
homeViewController = navController.viewControllers.first as? HomeViewController
}
And then to get the value of someString from within DetailViewController:
var stringFromRoot = homeViewController.someString
Is this the proper way to access properties of the root view controller in a UINavigationController? It does work in my testing, but if it has errors or drawbacks, or if there is a better way, I would like to know about that.
This is the only way I know of accessing the root view controller in a UINavigationController
. You asked about drawbacks, so here is one:
You can change the navigation controller's view controller's on the fly with setViewControllers(_:, animated:)
so it might not be a good long term strategy to assume that the root view controller will always be HomeViewController
It looks like you're using your navigation controller as a singleton to store and retrieve constants. Unless someString
depends on some value in your navigation controller, it would be more maintainable to extract that out to some kind of Constants
struct.