Does anyone know what the difference is between
TabBarController* tabBar = (TabBarController *)_window.rootViewController;
UINavigationController* navigationController = tabBar.selectedViewController;
ViewController* initialViewController = (ViewController *)navigationController.topViewController;
and this
UINavigationController* navigationController = [UIApplication sharedApplication].keyWindow.rootViewController.navigationController;
ViewController* initialViewController = (ViewController *)navigationController.topViewController;
My assumptions:
In example A I am using a specific nav stack (can't rely on that stack because I am trying to handle presenting a VC upon returning to the app after universal linking and it won't always be available).
In example B I am attempting to access the navigation stack I am currently on.
Last line of both examples, I am trying to push the new VC on top of the stack.
My results :
Putting aside design principles (example B seems hacky right now, but it is all I have thus far), I don't really understand the difference in these 2 examples, shouldn't they perform the same? Could anyone shine a light on why these are different ?
The navigationController property on UIViewController is nullable, so it may return nil.
The topViewController property on UINavigationController is also nullable, and returns a UIViewController?, not a specific class. Simply casting any UIViewController to ViewController is not safe, so you should be checking against isKindOfClass.
Same thing applies for rootViewController, it may not always be a TabBarController, so casting it unconditionally is unsafe.