所有的C語言編寫的程序,其執(zhí)行入口都是main()函數(shù),objective-c是基于C語言的面向?qū)ο蟮臄U(kuò)展和修改,同樣,所有的oc程序的執(zhí)行入口同樣是main()函數(shù).下面我們來簡單分析一下iOS應(yīng)用程序的main()函數(shù).
我們新建一個(gè)測(cè)試程序,該測(cè)試程序僅僅在屏幕上顯示一個(gè)Button按鈕.我們打開新建好的應(yīng)用程序代碼窗口,如下圖所示:
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
這段代碼的UIApplicationMain函數(shù)會(huì)創(chuàng)建一個(gè)UIApplication對(duì)象,每個(gè)iOS應(yīng)用程序有且僅有一個(gè)UIApplication對(duì)象,該對(duì)象的作用是維護(hù)運(yùn)行循環(huán).一旦程序啟動(dòng),就會(huì)創(chuàng)建這個(gè)UIApplication對(duì)象,該對(duì)象的運(yùn)行循環(huán)就會(huì)一直循環(huán)下去,main()函數(shù)也進(jìn)入阻塞狀態(tài).
Apple文檔對(duì)UIApplicationMain函數(shù)的描述如下:
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.
正是因?yàn)閙ain()函數(shù)進(jìn)入阻塞狀態(tài),因此即使這個(gè)函數(shù)有int形的返回值,卻總是不能返回這個(gè)值.
UIApplicationMain的另一個(gè)重要的功能就是創(chuàng)建一個(gè)指定類的對(duì)象,并設(shè)置為UIApplication對(duì)象的delegate.Apple文檔對(duì)該函數(shù)的詳細(xì)說明如下:
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.
由文檔可知,改對(duì)象的類由最后一個(gè)參數(shù)指定,該實(shí)參的類型是NSString,代表的是某個(gè)類的類名.因此我們創(chuàng)建的示例代碼中,UIApplicationMain會(huì)創(chuàng)建一個(gè)AppDelegate對(duì)象,并將其設(shè)置為UIApplication對(duì)象的delegate.
在應(yīng)用程序啟動(dòng),進(jìn)入runloop并開始接收事件前,UIApplication對(duì)象會(huì)向其委托發(fā)送一個(gè)特定的消息,讓應(yīng)用能夠完成相應(yīng)的初始化工作.這個(gè)特定的消息就是我們?cè)贏ppDelegate.m文件中的
application:applicationdidFinishLaunchingWithOptions:.一般而言我們可以直接修改此方法,實(shí)現(xiàn)我們需要的初始化功能.