標籤:style blog class code color int
UIKit是用來開發iOS的應用的,AppKit是用來開發Mac應用的,在使用過程中他們很相似,可是又有很多不同之處,通過對比分析它們的幾個核心對象,可以避免混淆。
UIKit和AppKit都有一個Application類,每個應用都只建立一個Application對象,分別是UIAplication和NSApplication的執行個體。但是建立這個對象的方式還是稍有不同,看iOS應用的main函數:
?
| 1 2 3 4 5 6 |
int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } |
再看Mac應用的main函數:
?
| 1 2 3 4 |
int main(int argc, const char * argv[]) { return NSApplicationMain(argc, argv); } |
UIApplicationMain
This function instantiates the application object from the principal class and instantiates the delegate (if any) from the given class and sets the delegate for the application. It also sets up the main event loop, including the application’s run loop, and begins processing events. If the application’s Info.plist file specifies a main nib file to be loaded, by including the NSMainNibFile key and a valid nib file name for the value, this function loads that nib file.
NSApplicationMain
Creates the application, loads the main nib file from the application’s main bundle, and runs the application. You must call this function from the main thread of your application, and you typically call it only once from your application’s main function, which is usually generated automatically by Xcode.
概括來說,主要都是建立Application對象,set up event loop,並開始處理event。區別是iOS上可以提供自訂的UIApplication,Application delegate是在main函數中指定的。
而Mac上Application Delegate是在nib/xib 檔案中指定的,而且NSApplicationMain會讀取Info.plist,得到main xib檔案,並載入進來,如果main xib資訊不存在或者不正確,程式就無法運行。相對應的,iOS應用使用Storyboard,iOS應用可以指定一個Main storyboard,然後由UIApplicationMain自動載入,但是這不是必須,如果不指定,程式也可以啟動,如果什麼都不做,就顯示黑屏,但Xcode會為Empty Application手動建立Window對象,這樣啟動後就顯示空白了,但如果指定就要指定正確,否則就會無法啟動了。如果不在Info.plist中指定,依然可以在Application Delegate 的 - (void)applicationDidFinishLaunching:(NSNotification *)notification; 中設定,比如下面的例子:
?
| 1 2 3 4 5 6 7 8 9 10 11 |
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; XIBViewController *controller = [[XIBViewController alloc] initWithNibName:@"XIBViewController" bundle:[NSBundle mainBundle]]; self.window.rootViewController = controller; return YES; } |
上面這段代碼手動建立Window對象,並建立root UIViewController,這樣也是可以正常顯示的。
下面再說說Window對象。在Mac和iOS上,一個Application都是可以建立多個Window對象的。iOS上在任一時刻只有一個key window,key window就是最後一個被發送了makeKeyAndVisible的Window。Mac上一個Application有多個Window是很容易理解的,iOS上的多個Window是怎樣工作的呢?閱讀https://developer.apple.com/library/ios/documentation/windowsviews/conceptual/viewpg_iphoneos/CreatingWindows/CreatingWindows.html
下面看看Window和View以及ViewController的關係。
UIWindow只需要一個rootViewController,