keyWindow与delegate中Window的区别

keyWindow与delegate中Window的区别-LMLPHP

源码:

//
// ViewController.m
// UIWindowRelated
//
// Created by YouXianMing on 14/10/25.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"-------");
NSLog(@"%@", [UIApplication sharedApplication].keyWindow);
NSLog(@"%@", [[[UIApplication sharedApplication] delegate] window]);
} - (void)viewDidAppear:(BOOL)animated {
NSLog(@"#######");
NSLog(@"%@", [UIApplication sharedApplication].keyWindow);
NSLog(@"%@", [[[UIApplication sharedApplication] delegate] window]);
} @end

结果如下图:

keyWindow与delegate中Window的区别-LMLPHP

从打印结果中可以知道:

keyWindow与delegate中的window其实是一样的,keyWindow的存在的意义,其实就是为了说明当前的window接管了这个控制器的view而已,你可以在keyWindow上加载你自己的建立的view了。

现在提供一个便利的类目^_^:

//
// UIWindow+Window.h
// Window
//
// Created by YouXianMing on 14-10-10.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import <UIKit/UIKit.h> @interface UIWindow (Window) /**
* 返回keyWindow(如果keyWindow有值,代表着你可以给window添加view了)
*
* @return 可以添加view并显示出来的window(如果返回为nil,说明你不能将view添加到window上去显示)
*/
+ (UIWindow *)usableWindow; /**
* 返回window
*
* @return window(你给这个window添加的view很有可能被控制器的view覆盖而显示不了)
*/
+ (UIWindow *)rootWindow; @end
//
// UIWindow+Window.m
// Window
//
// Created by YouXianMing on 14-10-10.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "UIWindow+Window.h" @implementation UIWindow (Window) + (UIWindow *)usableWindow
{
return [UIApplication sharedApplication].keyWindow;
} + (UIWindow *)rootWindow
{
return [[[UIApplication sharedApplication] delegate] window];
} @end
05-08 15:03