感謝喵神的《100個Swift開發(fā)必備 Tip》 內(nèi)容參考自 “Tip43 @UIApplicationMain”
- 在C系語言中,程序的入口都是
main
函數(shù),對于熟悉的 OC APP 項目,Xcode自動幫我們新建了一個 main.m 文件,其中就有 main 函數(shù):
int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
======================== 樸實無華的分割線 =====================
- but 在 swift 項目里,不曾找到 main 文件,也沒有
main
函數(shù)。唯一和 main 有關(guān)系的是默認的 APPDelegate 類的申明上方有個 @UIApplicationMain 的標簽。 - 猜測:這個標簽的作用就是將被標注的類作為委托,去創(chuàng)建一個
UIApplication 并啟動應(yīng)用程序。在編譯的時候,編譯器將尋找這個標記的類,并自動插入像 main 函數(shù)這樣的模塊代碼,從而實現(xiàn)和 OC 類似的效果。
@UIApplicationMain
注釋掉@UIApplicationMain標記?
程序編譯不通過,直接報錯!
Undefined symbols for architecture x86_64:
"_main", referenced from:
implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
意思應(yīng)該是找不到main函數(shù)
那么我們可以嘗試一下,創(chuàng)建一個main.swift文件,里面寫上和OC類似的代碼
import UIKit
class MyApplication: UIApplication {
}
UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate))
- 此時,如果再打開@UIApplicationMain標記,編譯就報錯了:
'UIApplicationMain' attribute cannot be used in a module that contains top-level code
一山不能容二虎!呵呵!!!
既然是自己創(chuàng)建的main.swift文件,那么我們可以用它做哪些事情呢?
可以全局監(jiān)聽事件
- 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.
///
/// @param argc The count of arguments in argv; this usually is the corresponding parameter to main.
/// @param argv A variable list of arguments; this usually is the corresponding parameter to main.
/// @param principalClassName The name of the UIApplication class or subclass. If you specify nil, UIApplication is assumed.
/// @param delegateClassName 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.
///
/// @return Even though an integer return type is specified, this function never returns.
public func UIApplicationMain(argc: Int32, _ argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>>, _ principalClassName: String?, _ delegateClassName: String?) -> Int32
- 第三個參數(shù)說明:如果傳入nil,則使用UIApplication
那么如果我不傳入nil,傳入自定義的類MyApplication呢?
- 如果傳入自定義的類,那么我們就可以在類中重寫父類的方法,做一些攔截性操作,監(jiān)聽某些事件了!
import UIKit
class MyApplication: UIApplication {
override func sendEvent(event: UIEvent) {
super.sendEvent(event)
print("sendEvent")
}
}
// 第三個參數(shù)不要傳nil
UIApplicationMain(Process.argc, Process.unsafeArgv, NSStringFromClass(MyApplication), NSStringFromClass(AppDelegate))