UIApplication 物件就是應用程式本身的象徵,一個物件對應一個 App。每個應用都有自己的 UIApplication,而且是單例;試圖用 alloc 再建一個,執行期會直接報錯。
取得方式很簡單:[UIApplication sharedApplication]。iOS 程式啟動後建立的第一個物件就是它,且只有一個(連續印兩次位址會發現完全相同)。
有了它,就能做一些應用層級的操作。
就像 QQ 有幾條新訊息,圖標上就顯示幾。
@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
{
NSLog(@"按鈕點擊事件");
//錯誤,只能有一個唯一的UIApplication對象,不能再進行創建
// UIApplication *app=[[UIApplication alloc]init];
//通過sharedApplication獲取該程序的UIApplication對象
UIApplication *app=[UIApplication sharedApplication];
app.applicationIconBadgeNumber=123;
}

@property(nonatomic,getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
//設置指示器的聯網動畫
app.networkActivityIndicatorVisible=YES;

從 iOS 7 開始,系統提供兩種管理狀態欄的方式。
a. 由 UIViewController 管理,好處是每個控制器都能有自己獨立的狀態欄樣式。iOS 7 預設就走這條路,只要實作兩個方法即可:
- (UIStatusBarStyle)preferredStatusBarStyle;
-(BOOL)prefersStatusBarHidden;
#pragma mark-設置狀態欄的樣式
-(UIStatusBarStyle)preferredStatusBarStyle
{
//設置為白色
//return UIStatusBarStyleLightContent;
//默認為黑色
return UIStatusBarStyleDefault;
}
#pragma mark-設置狀態欄是否隱藏(否)
-(BOOL)prefersStatusBarHidden
{
return NO;
}
b. 由 UIApplication 統一管理整個應用的狀態欄。要走這條路,得先改 Info.plist 裡對應的設定。

//通過sharedApplication獲取該程序的UIApplication對象
UIApplication *app=[UIApplication sharedApplication];
app.applicationIconBadgeNumber=123;
//設置指示器的聯網動畫
app.networkActivityIndicatorVisible=YES;
//設置狀態欄的樣式
//app.statusBarStyle=UIStatusBarStyleDefault;//默認(黑色)
//設置為白色+動畫效果
[app setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
//設置狀態欄是否隱藏
app.statusBarHidden=YES;
//設置狀態欄是否隱藏+動畫效果
[app setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
該怎麼選?如果整個 App 的狀態欄樣式固定不變,用 UIApplication 管理更省事,而且能帶動畫;如果需要依頁面切換樣式或隱藏,就交給各控制器。
- (BOOL)openURL:(NSURL*)url;
打電話:
[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。
順帶理解 URL 的本質:統一資源定位符,用來唯一標示一個資源,格式是「協議頭://主機位址/資源路徑」。網路資源如 https://www.baidu.com/images/20140603/abc.png,本地資源則像 file:///users/apple/desktop/abc.png,主機位址可省略。
行動系統有個致命特性:App 極易被打斷。一通來電、一次鎖屏,App 就可能被切到背景甚至終止。這些干擾會產生系統事件,UIApplication 會把它們轉交給 delegate 處理。

每次新建專案都會有一個帶 AppDelegate 字樣的類,它就是 UIApplication 的代理,預設已遵守 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");
}
// 應用程序即將被銷毀的時候會調用該方法
// 注意:如果應用程序處於掛起狀態的時候無法調用該方法
- (void)applicationWillTerminate:(UIApplication *)application
{
}
// 應用程序接收到內存警告的時候就會調用
// 一般在該方法中釋放掉不需要的內存
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
NSLog(@"MemoryWarning");
}
@end
其中 applicationWillTerminate: 有個實務上的坑:如果 App 正處於掛起狀態,這個方法不會被觸發。所以別把關鍵資料的保存只押在它身上,應該在進入背景時就存好。
main 函數裡只有一句關鍵程式碼:
int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
argc、argv:直接傳入即可。
principalClassName:指定應用程式類名,必須是 UIApplication 或其子類,傳 nil 則預設用 UIApplication。
delegateClassName:指定代理類,必須遵守 UIApplicationDelegate 協議。
UIApplicationMain 內部做了四件事:依第三個參數建立 UIApplication 物件、依第四個參數建立 delegate 物件、把 delegate 指派給 UIApplication 的 delegate 屬性、然後啟動 App 的主 Runloop 進入事件循環(啟動完成後會回呼 application:didFinishLaunchingWithOptions:)。只有程式正常結束時,這個函數才會返回。
#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", NSStringFromClass([YYAppDelegate class]));
/*
argc: 系統或者用戶傳入的參數個數
argv: 系統或者用戶傳入的實際參數
1.根據傳入的第三個參數創建UIApplication對象
2.根據傳入的第四個產生創建UIApplication對象的代理
3.設置剛剛創建出來的代理對象為UIApplication的代理
4.開啟一個事件循環
*/
return UIApplicationMain(argc, argv, @"UIApplication", @"YYAppDelegate");
}
這個事件循環可以理解為一個先進先出的佇列:先送進去的先處理。

1)main 函數
2)UIApplicationMain
· 建立 UIApplication 物件
· 建立 UIApplication 的 delegate 物件
3)delegate 開始處理系統事件(無 storyboard 的情況)
· 啟動完成,回呼 application:didFinishLaunchingWithOptions:
· 在其中建立 UIWindow
· 建立並設定 UIWindow 的 rootViewController
· 顯示視窗
3')有 storyboard 時,依 Info.plist 找到主 storyboard 並載入
· 建立 UIWindow
· 建立並設定 rootViewController
· 顯示視窗
也就是說,用了 storyboard 之後,前面那三件建立視窗的事系統會代勞,didFinishLaunching 裡就不必再自己寫。
plist 結構與專案檔案:

這個範例的重點在「模型套模型」:一個品牌分組裡含多輛車,因此 YYcarsgroup 內部還得有一個 YYcars 陣列。
YYcarsgroup.h:
#import <Foundation/Foundation.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 *yycars=[[YYcars alloc]initWithDict:dict];
[arrayM addObject:yycars];
}
self.cars=arrayM;
}
return self;
}
+(instancetype)carsgroupWithDict:(NSDictionary *)dict
{
return [[self alloc]initWithDict:dict];
}
@end
用 arrayWithCapacity: 預先配置容量是個小習慣,元素多時能少幾次扩容複製。
YYcars.h:
#import <Foundation/Foundation.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:
#import "YYcars.h"
@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- 實現懶加載
//1.從包中讀取數據
//2.字典轉模型
//3.返回cars
-(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 *carsgroup=[YYcarsgroup carsgroupWithDict:dict];
[carsarray addObject:carsgroup];
}
_car=[carsarray copy];
}
return _car;
}
#pragma mark- 實現tableview的數據展示
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.car.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
YYcarsgroup *carsgroup=self.car[section];
return carsgroup.cars.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier=@"car";
//4.1去緩存中去取cell
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
//4.2若沒有,則創建cell,並蓋章
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
//4.3設置cell的數據
YYcarsgroup *carsgroup=self.car[indexPath.section];
YYcars *yycars=carsgroup.cars[indexPath.row];
cell.imageView.image=[UIImage imageNamed:yycars.icon];
cell.textLabel.text=yycars.name;
//4.4返回cell
return cell;
}
//設置每組的標題
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
YYcarsgroup *carsgroup=self.car[section];
return carsgroup.title;
}
//設置索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
//利用kvc取出所有的標題
NSArray *title=[self.car valueForKeyPath:@"title"];
return title;
}
//隱藏狀態欄
-(BOOL)prefersStatusBarHidden
{
return YES;
}
@end
效果:

1)右側索引列用 KVC 一行搞定。valueForKeyPath:@"title" 會遍歷陣列,把每個 group 的 title 收集成新陣列,不必手寫迴圈。
2)cell 的重複使用是效能關鍵。先從佇列取,取不到才建立,並透過 reuseIdentifier 標記身份:
static NSString *identifier=@"car";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
嵌套模型之所以值得花力氣做,正是因為它把「一組多項」的結構在資料層就整理乾淨了:numberOfRowsInSection 只需問 group.cars.count,cellForRow 只需兩層下標,控制器的邏輯一目了然。