两种获取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 = ; layer = >

window2 = ; layer = >

window1.rootViewController = 

window2.rootViewController = 

分析

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

运用

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

if ([[UIApplication sharedApplication].delegate.window.rootViewController isKindOfClass:["某rootVC" class]]) {
        
}

你可能感兴趣的:(两种获取rootViewController区别)