keyWindow误区 和UIApplicationRotati

2017-12-18  本文已影响0人  Trigger_o

获取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

上一篇 下一篇

猜你喜欢

热点阅读