美文网首页
keyWindow误区 和UIApplicationRotati

keyWindow误区 和UIApplicationRotati

作者: Trigger_o | 来源:发表于2017-12-18 11:24 被阅读0次

获取window一般有两种方法

(1)UIWindow *window1 = [UIApplication sharedApplication].keyWindow;

(2)AppDelegate *appdelegate = (AppDelegate*)[UIApplicationsharedApplication].delegate;

UIWindow *window2 = appdelegate.window;

这里的keyWindow与window事实上很多时候并不相等

当界面上出现系统alert等模态视图的时候

UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"测试" message:@"测试" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
[alterView show];
UIWindow *window1 = [UIApplication sharedApplication].keyWindow;
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
UIWindow *window2 = appdelegate.window;
NSLog(@"\n\nwindow1 = %@    \n\nwindow2 = %@  \n\nwindow1.rootViewController = %@ \n\nwindow2.rootViewController = %@",window1,window2,window1.rootViewController,window2.rootViewController);

打印结果如下

可见keyWindow已经不是我们希望的window对象了,而是alert的window

此时再去获取rootViewController更是错误的

这种问题会引起一些crash比如

追踪受限[EXC_BREAKPOINT // SIGTRAP],在出错堆栈中可以看到_UIAlertControllerShimPresenterWindow

相关文章

网友评论

      本文标题:keyWindow误区 和UIApplicationRotati

      本文链接:https://www.haomeiwen.com/subject/pemuyttx.html