iosobjective-cuinavigationcontrollerwindowrootviewcontroller

(Objective-C) Difference between accessing the navigation stack through the window.rootView and keyWindow


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:

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 ?


Solution

    1. The navigationController property on UIViewController is nullable, so it may return nil.

    2. 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.

    3. Same thing applies for rootViewController, it may not always be a TabBarController, so casting it unconditionally is unsafe.