每個 iOS App 在啟動時建立的第一個物件就是 UIApplication,它是整個應用程式的象徵,而且以單例形式存在——試著 alloc 一個新的出來,程式會直接報錯。要取得它,唯一途徑是 [UIApplication sharedApplication]。
有了這個物件,就能執行一些「App 層級」的操作。
就是 QQ、Mail 那種在圖示右上角顯示未讀數量的小紅點:
@property (nonatomic) NSInteger applicationIconBadgeNumber;
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 60, 30)];
[btn setTitle:@"按鈕" forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor brownColor]];
[btn addTarget:self action:@selector(onClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
- (void)onClick {
// UIApplication *app = [[UIApplication alloc] init]; // 錯誤:唯一性不容侵犯
UIApplication *app = [UIApplication sharedApplication];
app.applicationIconBadgeNumber = 123;
}

@property (nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; app.networkActivityIndicatorVisible = YES;

從 iOS 7 開始,狀態列可以由兩個地方掌控。
方法一:交給 UIViewController。這是 iOS 7 之後的預設行為,每個控制器都能擁有自己的狀態列樣式,只要覆寫兩個方法:
#pragma mark - 狀態列樣式
- (UIStatusBarStyle)preferredStatusBarStyle {
// return UIStatusBarStyleLightContent; // 白色
return UIStatusBarStyleDefault; // 預設黑色
}
#pragma mark - 狀態列是否隱藏
- (BOOL)prefersStatusBarHidden {
return NO;
}
方法二:交給 UIApplication 統一管理。要先到 Info.plist 把「View controller-based status bar appearance」關掉,才會生效。

UIApplication *app = [UIApplication sharedApplication]; app.applicationIconBadgeNumber = 123; app.networkActivityIndicatorVisible = YES; // [app setStatusBarStyle:UIStatusBarStyleLightContent animated:YES]; app.statusBarHidden = YES; [app setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
該選哪一個?若樣式從頭到尾只有一種,用 UIApplication 設定即可,還能額外獲得動畫效果;若不同頁面需要不同的隱藏狀態與樣式,就該交由各控制器自行管理。
- (BOOL)openURL:(NSURL *)url; UIApplication *app = [UIApplication sharedApplication]; [app openURL:[NSURL URLWithString:@"tel://10086"]]; // 撥號 [app openURL:[NSURL URLWithString:@"sms://10086"]]; // 簡訊 [app openURL:[NSURL URLWithString:@"mailto://12345@qq.com"]]; // 郵件 [app openURL:[NSURL URLWithString:@"https://ios.itcast.cn"]]; // 網頁 // 也可以換成其他 App 註冊的 scheme,直接喚起該 App
補充一個基礎概念:URL(統一資源定位符)用來唯一標示一項資源,格式為「協議頭://主機位址/資源路徑」。網路資源如 https://www.baidu.com/images/abc.png;本機資源則是 file:///users/apple/desktop/abc.png(主機位址省略)。
行動裝置有個先天弱點:App 隨時可能被來電、鎖屏、切換應用程式打斷,甚至被系統回收。每次狀態轉換時,UIApplication 都會通知它的 delegate 物件,交由代理決定如何反應。

每個新專案都會自動產生一個 AppDelegate 類別,它預設已符合 UIApplicationDelegate 協議。

#import "YYAppDelegate.h"
@implementation YYAppDelegate
// 啟動完成
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"didFinishLaunchingWithOptions");
return YES;
}
// 即將失去焦點(不可互動)
- (void)applicationWillResignActive:(UIApplication *)application {
NSLog(@"ResignActive");
}
// 重新取得焦點(可互動)
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(@"BecomeActive");
}
// 進入背景:適合在這裡保存資料與狀態
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"Background");
}
// 即將回到前台:適合在這裡恢復資料與狀態
- (void)applicationWillEnterForeground:(UIApplication *)application {
NSLog(@"Foreground");
}
// 即將被銷毀(若 App 處於掛起狀態則不會被呼叫)
- (void)applicationWillTerminate:(UIApplication *)application {
}
// 收到記憶體警告:清掉用不到的資源
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
NSLog(@"MemoryWarning");
}
@end
打開 main.m,會看到一個關鍵函式:
int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
四個參數中,後兩個才是重點:
principalClassName:指定 App 的主類別,必須是 UIApplication 或其子類別;傳 nil 時預設使用 UIApplication。delegateClassName:指定代理類別,該類別必須符合 UIApplicationDelegate 協議。#import <UIKit/UIKit.h>
#import "YYAppDelegate.h"
int main(int argc, char *argv[]) {
@autoreleasepool {
// return UIApplicationMain(argc, argv, nil, NSStringFromClass([YYAppDelegate class]));
return UIApplicationMain(argc, argv, @"UIApplication", @"YYAppDelegate");
}
}
UIApplicationMain 內部依序完成四件事:依第三個參數建立 UIApplication 物件 → 依第四個參數建立 delegate 物件 → 把 delegate 指派給 UIApplication → 啟動主 Run Loop 進入事件循環。啟動完成後,delegate 的 application:didFinishLaunchingWithOptions: 會被呼叫;只有當 App 正常結束,這個函式才會返回。

沒有 storyboard 的專案:
UIApplicationMainUIApplication 物件與它的 delegateapplication:didFinishLaunchingWithOptions:UIWindow、設定 rootViewController、呼叫 makeKeyAndVisible 顯示視窗有 storyboard 的專案:系統會從 Info.plist 讀出主 storyboard 檔名並自動載入,上述建立視窗、設定根控制器、顯示視窗的三個步驟都由系統代勞。
plist 的結構是「陣列包著字典,字典裡的 cars 又是一個字典陣列」,這正是典型的巢狀模型情境。

// YYcarsgroup.h @interface YYcarsgroup : NSObject @property (nonatomic, copy) NSString *title; @property (nonatomic, strong) NSArray *cars; - (instancetype)initWithDict:(NSDictionary *)dict; + (instancetype)carsgroupWithDict:(NSDictionary *)dict; @end
// YYcarsgroup.m —— 重點在「字典轉模型」的巢狀處理
#import "YYcarsgroup.h"
#import "YYcars.h"
@implementation YYcarsgroup
- (instancetype)initWithDict:(NSDictionary *)dict {
if (self = [super init]) {
self.title = dict[@"title"];
NSArray *dictCars = dict[@"cars"];
// 預先配置容量,可少幾次陣列擴容,效能更好
NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:dictCars.count];
for (NSDictionary *dict in dictCars) {
YYcars *cars = [[YYcars alloc] initWithDict:dict];
[arrayM addObject:cars];
}
self.cars = arrayM;
}
return self;
}
+ (instancetype)carsgroupWithDict:(NSDictionary *)dict {
return [[self alloc] initWithDict:dict];
}
@end
// YYcars.h @interface YYcars : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *icon; - (instancetype)initWithDict:(NSDictionary *)dict; + (instancetype)carsWithDict:(NSDictionary *)dict; @end
// YYcars.m
@implementation YYcars
- (instancetype)initWithDict:(NSDictionary *)dict {
if (self = [super init]) {
self.name = dict[@"name"];
self.icon = dict[@"icon"];
}
return self;
}
+ (instancetype)carsWithDict:(NSDictionary *)dict {
return [[self alloc] initWithDict:dict];
}
@end
// YYViewController.m
#import "YYViewController.h"
#import "YYcarsgroup.h"
#import "YYcars.h"
@interface YYViewController () <UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UITableView *tableview;
@property (nonatomic, strong) NSArray *car;
@end
@implementation YYViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableview.rowHeight = 60.f;
self.tableview.dataSource = self;
}
#pragma mark - 懶載入:讀 plist -> 字典轉模型 -> 回傳陣列
- (NSArray *)car {
if (_car == nil) {
NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"cars_total.plist" ofType:nil];
NSArray *arrayM = [NSArray arrayWithContentsOfFile:fullPath];
NSMutableArray *carsArray = [NSMutableArray array];
for (NSDictionary *dict in arrayM) {
YYcarsgroup *group = [YYcarsgroup carsgroupWithDict:dict];
[carsArray addObject:group];
}
_car = [carsArray copy];
}
return _car;
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.car.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
YYcarsgroup *group = self.car[section];
return group.cars.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"car";
// 先從重用池取,取不到才建立
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
YYcarsgroup *group = self.car[indexPath.section];
YYcars *cars = group.cars[indexPath.row];
cell.imageView.image = [UIImage imageNamed:cars.icon];
cell.textLabel.text = cars.name;
return cell;
}
// 每組的標題
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
YYcarsgroup *group = self.car[section];
return group.title;
}
// 右側索引列:用 KVC 一次取出所有組標題
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [self.car valueForKeyPath:@"title"];
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
@end

兩個值得留意的細節:索引列靠 valueForKeyPath:@"title" 一行搞定,不必手動遍歷;cell 則一律走「先取重用池、再建立並帶上 identifier」的固定寫法,這是列表效能的底線。