What is the difference between UIApplication.sharedApplication.delegate.window and UIApplication.sharedApplication.keyWindow?

前端 未结 4 1774
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 19:44

Can anyone help me understand the difference between the following two lines:

[UIApplication.sharedApplication.delegate.window addSubview:myView];

4条回答
  •  清歌不尽
    2020-12-04 20:06

    Basheer_CAD's answer is not right. They are not always the same in iOS.

    Jeffery Thomas's answer is right and let me provide a concrete example.

    - (void)viewDidLoad {
        [super viewDidLoad];
        NSLog(@"keyWindow --------> %@",[UIApplication sharedApplication].keyWindow.rootViewController);
        NSLog(@"delegate.window --> %@",[UIApplication sharedApplication].delegate.window.rootViewController);
        NSLog(@"self.view.window -> %@",self.view.window.rootViewController);
    }
    
    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
        [alert show];
        NSLog(@"keyWindow --------> %@",[UIApplication sharedApplication].keyWindow.rootViewController);
        NSLog(@"delegate.window --> %@",[UIApplication sharedApplication].delegate.window.rootViewController);
        NSLog(@"self.view.window -> %@",self.view.window.rootViewController);
    }
    

    The output is:

    keyWindow --------> (null)
    delegate.window --> 
    self.view.window -> (null)
    keyWindow --------> 
    delegate.window --> 
    self.view.window -> 
    

    When viewDidLoad, actually the window is not ready yet, so there is nothing for the system window. UIAlertView may dominate the window, so you cannot get the window you want.

提交回复
热议问题