两种获取rootViewController区别

获取的两种方式

第一种 [UIApplication sharedApplication].keyWindow.rootViewController;
第二种 [UIApplication sharedApplication].delegate.window.rootViewController;

什么是keyWindow?

苹果文档显示
This property holds the UIWindow object in the windows array that is most recently sent the makeKeyAndVisible message.

测试

  • Appdelegate设置
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc] init]];
    [self.window makeKeyAndVisible];
    return YES;
}
  • viewController弹出alertView 此时比较获取结果
- (void)testWindow {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"DDY"
                                                    message:@"window获取测试"
                                                   delegate:self
                                          cancelButtonTitle:@"Cancel"
                                          otherButtonTitles:@"OtherBtn",nil];
    [alert show];
    
    UIWindow *window1 = [UIApplication sharedApplication].keyWindow;
    UIWindow *window2 = [UIApplication sharedApplication].delegate.window;
    
    NSLog(@"window1 = %@\n\nwindow2 = %@\n\nwindow1.rootViewController = %@\n\nwindow2.rootViewController = %@",window1,window2,window1.rootViewController,window2.rootViewController);
}

打印结果

window1 = <_UIAlertControllerShimPresenterWindow: 0x14fd32dd0; frame = (0 0; 375 667); opaque = NO; gestureRecognizers = <NSArray: 0x14fd27bd0>; layer = <UIWindowLayer: 0x14fd65ff0>>

window2 = <UIWindow: 0x14fd5fb60; frame = (0 0; 375 667); gestureRecognizers = <NSArray: 0x14fd548c0>; layer = <UIWindowLayer: 0x14fd04960>>

window1.rootViewController = <UIApplicationRotationFollowingController: 0x14fe9ca70>

window2.rootViewController = <DDYTabBarController: 0x14fe5f350>

分析

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

运用

由于我们想要的是第二种方式获取的结果,所以

if ([[UIApplication sharedApplication].delegate.window.rootViewController isKindOfClass:["某rootVC" class]]) {
        
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容