[iOS基础控件 - 6.10.6] UIApplicationDelegate & 程序启动过程
A.概念
1.移动app非常容易受到其他的系统、软件事件的干扰,如来电、锁屏
2.app受到干扰的时候,UIApplication会通知delegate,来代理处理干扰事件
3.delegate可以处理的事件
(1)app声明周期(启动、关闭)
(2)系统事件(来电)
(3)紧急事件(内存警告)
B.使用
称为delegate的条件:遵守UIApplicationDelegate协议
项目开始会自动创建:AppDelegate
1.delegate方法
1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 2 NSLog(@"app启动完毕的时候调用"); 3 return YES; 4 } 5 6 - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { 7 NSLog(@"app接收到内存警告时调用"); 8 } 9 10 - (void)applicationDidEnterBackground:(UIApplication *)application { 11 NSLog(@"app进入后台的时候调用"); 12 } 13 14 - (void)applicationWillResignActive:(UIApplication *)application { 15 NSLog(@"app将要被挂起"); 16 } 17 18 - (void)applicationWillEnterForeground:(UIApplication *)application { 19 NSLog(@"app回到前台"); 20 } 21 22 - (void)applicationDidBecomeActive:(UIApplication *)application { 23 NSLog(@"app激活后"); 24 } 25 26 - (void)applicationWillTerminate:(UIApplication *)application { 27 NSLog(@"app将要关闭"); 28 } 29
(1)一般的app操作触发delegate代理监听事件流程:
(2)整个app的启动过程:
2.main函数中调用的UIApplicationMain函数
1 int main(int argc, char * argv[]) { 2 @autoreleasepool { 3 return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 4 } 5 }
函数定义:
UIKIT_EXTERN int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
(1)principalClassName
a.Application类名,必须是UIApplication或者其子类的类名
b.如果是nil,则默认是UIApplication
c.UIApplicationMain函数根据principalClassName创建UIApplication对象
(2)delegateClassName
a.delegate类名,此类必须遵守UIApplicationDelegate协议
b.UIApplicationMain函数根据delegateClassName创建一个delegate,并将其赋值给UIApplication的delegate属性
(3)进入Main Runloop 事件循环,使用delegate对事件进行监听
(4)程序正常退出,UIApplicationMain函数返回