在上一篇文章iOS开发:第一个iOS程序分析——代理,生命周期函数中主要介绍了iOS使用Objective-C开发的两个主要文件main.m和AppDelegate.m和控制程序生命周期的函数,接下来将介绍另外两个文件:AppDelegate.h文件、UIViewController.m文件和iOS开发中的View和ViewController。
打开AppDelegate.h文件:
先看一下AppDelegate类,前面说过,AppDelegate是作为Application的代理,这个程序中的AppDelegate不仅负责控制程序的生命周期,而且负责控制程序初始界面(初始StoryBoard)的显示,因此该代理类必须能够访问到初始界面的界面元素。
明白这点,就不难了解KZX AppDelegate类中为什么会有UIWindow的一个引用了。如下
该文件只有以下寥寥几行代码:
<span style="font-family:Comic Sans MS;font-size:14px;">#import <UIKit/UIKit.h>
@interface KZXAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
</span>
除去导入头文件的语句,文件由@interface开始声明到@end结束声明,可以看到,确实该代理类持有一个UIWindow类的实例,该UIWindow实例即代表了该视图控制器所负责控制显示的窗口视图(即一个屏幕界面),读者朋友可以尝试把这一句删去,会发现运行程序后是黑漆漆一片,因为代理无法找到应该在哪里显示视图。自然没有界面。
那么为什么代理要持有UIWindow的实例而不持有其他视图的实例呢?
先来看看官方文档对于视图的说明(View):
“Views not only display themselves onscreen and react to user input, they also serve as containers for other views. As a result, views in an app are arranged in a hierarchical structure called the view hierarchy. The view hierarchy defines the layout of views relative to other views. Within that hierarchy, view instances enclosed within a view are called subviews, and the parent view that encloses a view is referred to as its superview. Even though a view instance can have multiple subviews, it can have only one superview.At the top of the view hierarchy is the