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

获取工程中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。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容