self.view.widow 和 [[UIApplication sharedApplication] keyWindow] 在 Objective-C 中有什么区别

what's the difference between self.view.widow and [[UIApplication sharedApplication] keyWindow] in Objective-C

如果我喜欢这个

- (void)viewDidLoad {
    [super viewDidLoad];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"test" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
    [alert show];
}

// Called when a button is clicked. The red view and alert will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self showView];
}

// after animation ,this will work fine
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
//    [self showView];
}

- (void)showView {
    // Called when a button is clicked. The view will be automatically dismissed after this call returns
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, 200, 200);
    view.backgroundColor = [UIColor redColor];
    view.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2.0f, [UIScreen mainScreen].bounds.size.height/2.0f);
    //    [self.view.window addSubview:view]; //when i use this ,both of the two delegate methods works fine
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window addSubview:view];
}

那么在 alertView:clickedButtonAtIndex: 调用 returns

之后,红色视图和警报将自动消失

谁能告诉我原因?

self.view.widow 和 Objective-C 中的 [[UIApplication sharedApplication] keyWindow] 有什么区别

你的问题基本上在这里得到解决:

diffrence between [[[[UIApplication sharedApplication] delegate] window] and [[UIApplication sharedApplication].keyWindow?

为了将其与您的问题联系起来,UIAlertView 在系统 window 中显示,并且正是这个 window 是显示警报时的 keyWindow。当警报被解除时,window 消失,因此您的视图消失。

假设 self.view 是应用程序 window 的子视图(几乎总是如此),您的视图会继续显示,因为 window 本身会在警报后继续显示被解雇了。