浅析iOS应用中的main()和UIApplication

所有的C语言编写的程序,其执行入口都是main()函数,objective-c是基于C语言的面向对象的扩展和修改,同样,所有的oc程序的执行入口同样是main()函数.下面我们来简单分析一下iOS应用程序的main()函数.


我们新建一个测试程序,该测试程序仅仅在屏幕上显示一个Button按钮.我们打开新建好的应用程序代码窗口,如下图所示:

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

这段代码的UIApplicationMain函数会创建一个UIApplication对象,每个iOS应用程序有且仅有一个UIApplication对象,该对象的作用是维护运行循环.一旦程序启动,就会创建这个UIApplication对象,该对象的运行循环就会一直循环下去,main()函数也进入阻塞状态.


Apple文档对UIApplicationMain函数的描述如下:
This function is called in the main entry point to create the application object and the application delegate and set up the event cycle.
Even though an integer return type is specified, this function never returns. When users exits an iOS application by pressing the Home button, the application moves to the background.


正是因为main()函数进入阻塞状态,因此即使这个函数有int形的返回值,却总是不能返回这个值.


UIApplicationMain的另一个重要的功能就是创建一个指定类的对象,并设置为UIApplication对象的delegate.Apple文档对该函数的详细说明如下:

Declaration:

int UIApplicationMain (
   int argc,
   char * _Nonnull argv[],
   NSString *principalClassName,
   NSString *delegateClassName
);


Parameters

1.argc
The count of arguments in argv; this usually is the corresponding parameter to main.

2.argv
A variable list of arguments; this usually is the corresponding parameter to main.

3.principalClassName
The name of the UIApplication class or subclass. If you specify nil, UIApplication is assumed.

4.delegateClassName
The name of the class from which the application delegate is instantiated. If principalClassName designates a subclass of UIApplication, you may designate the subclass as the delegate; the subclass instance receives the application-delegate messages. Specify nil if you load the delegate object from your application’s main nib file.

由文档可知,改对象的类由最后一个参数指定,该实参的类型是NSString,代表的是某个类的类名.因此我们创建的示例代码中,UIApplicationMain会创建一个AppDelegate对象,并将其设置为UIApplication对象的delegate.

在应用程序启动,进入runloop并开始接收事件前,UIApplication对象会向其委托发送一个特定的消息,让应用能够完成相应的初始化工作.这个特定的消息就是我们在AppDelegate.m文件中的
application:applicationdidFinishLaunchingWithOptions:.一般而言我们可以直接修改此方法,实现我们需要的初始化功能.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值