iOS开发-获取rootViewController的正确方式

3,322 阅读1分钟

获取工程中window上面的RootViewController keyWindow是,在windows数组中最近时间调用makeKeyAndVisible方法的属性。

方法一:建议使用

AppDelegate *app =(AppDelegate *) [UIApplication sharedApplication].delegate;
UIViewController *rootViewController1 = appdelegate.window.rootViewController;
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if ([appdelegate.window.rootViewController isKindOfClass:["xxxrootVC" class]] == YES) {
        // 这样更保险
    }

方法二:不建议使用

UIAlertController或UIAlertView或UIActionSheet弹出后,keyWindow就会变成UIAlertControllerShimPresenterWindow这个类

UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIViewController *rootViewController2 = window.rootViewController;

alertView的出现是因为,生成了一个新的window,加在了界面上面。 这个时候获取到的keyWindow就是UIAlertControllerShimPresenterWindow。