一個(gè)Objective-C的APP項(xiàng)目中 會(huì)有一個(gè)main.m文件
內(nèi)部實(shí)現(xiàn)如下
int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil,
NSStringFromClass([AppDelegate class]));
}
}
在C語言中main函數(shù)是整個(gè)程序的入口 那么我們來看這個(gè)函數(shù)都做了什么事:
在這里我們調(diào)用了 UIKit 的 UIApplicationMain 方法窖剑。這個(gè)方法將根據(jù)第三個(gè)參數(shù)初始化一個(gè) UIApplication 或其子類的對(duì)象并開始接收事件 (在這個(gè)例子中傳入 nil卷雕,意味使用默認(rèn)的 UIApplication)。最后一個(gè)參數(shù)指定了 AppDelegate 類作為應(yīng)用的委托诽偷,它被用來接收類似 didFinishLaunching 或者 didEnterBackground 這樣的與應(yīng)用生命周期相關(guān)的委托方法。另外叁执,雖然這個(gè)方法標(biāo)明為返回一個(gè) int篙悯,但是其實(shí)它并不會(huì)真正返回。它會(huì)一直存在于內(nèi)存中夕凝,直到用戶或者系統(tǒng)將其強(qiáng)制終止宝穗。
Swift項(xiàng)目中,找不到像OC時(shí)的main文件 也不存在main函數(shù),但是在AppDelegate中有個(gè)@UIApplicationMain關(guān)鍵字,其實(shí)這個(gè)關(guān)鍵字所做的事情就是被標(biāo)注的類作為委托,去創(chuàng)建一個(gè)UIApplication并啟動(dòng)整個(gè)程序。
去掉@UIApplicationMain APP運(yùn)行時(shí)會(huì)報(bào)Undefined symbols _main
的錯(cuò)誤,說明找不到main函數(shù) 码秉。說明Swift項(xiàng)目中也是需要main函數(shù)的
我們可以自己創(chuàng)建一個(gè)main.swift文件就像C中的main.c OC中的main.m,在這個(gè)文件中不用定義作用域,我們創(chuàng)建一個(gè)Swift語言的commandLineTool程序時(shí)就會(huì)發(fā)現(xiàn)main.swift文件下只有以下代碼
import Foundation
print("Hello, World!")
這個(gè)文件中的代碼將會(huì)作為main函數(shù)執(zhí)行
只需要在這個(gè)文件下寫下:
UIApplicationMain(
CommandLine.argc,
UnsafeMutableRawPointer(CommandLine.unsafeArgv)
.bindMemory(
to: UnsafeMutablePointer<Int8>.self,
capacity: Int(CommandLine.argc)),
nil,
NSStringFromClass(AppDelegate.self)
)
第三個(gè)參數(shù)傳nil是使用系統(tǒng)默認(rèn)創(chuàng)建的UIApplication
當(dāng)然我們也可以創(chuàng)建自己的UIApplication 以監(jiān)聽每次事件的發(fā)送(比如點(diǎn)擊了某個(gè)按鈕)
class MyApplication: UIApplication {
override func sendAction(_ action: Selector, to target: Any?, from sender: Any?, for event: UIEvent?) -> Bool {
print(sender)
return super.sendAction(action, to: target, from: sender, for: event)
}
}