I was surprised to observe that within didFinishLaunchingWithOptions a call to [UIApplication sharedApplication].keyWindow.rootViewController returns nil.

I want to set some things up once on app launch where I need to reference the rvc, however this behavior means I'll have to do it elsewhere. If it can't be done in didFinishLaunchingWithOptions then the only other choice is applicationDidBecomeActive? But with the additional irritation (a small irritation, but still you'd think it shouldn't have to be necessary) of having to have a flag to ensure the set up steps only happens once and not every time appliationDidBecomeActive is called.

Is there somewhere else I can access the rootViewController on app launch to set additional steps up once?

有帮助吗?

解决方案

There isn't a keyWindow at that time in the application lifecycle, so the reason there's no rootViewController to get on the keyWindow is because keyWindow is nil. But the app delegate has a property for your window, so you can just get self.window.rootViewController.

However, if you always have the same root view controller, you could probably do at least some of what you want to do (maybe all of it) in your root view controller's viewDidLoad method. This generally should only ever be called once, because with iOS 6 and later your offscreen view controllers' views are never unloaded.

其他提示

You can get it from window:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UIViewController *rootViewController = self.window.rootViewController;

    return YES;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top