iOS 應用效能優化並非高深莫測,掌握核心原則與常見陷阱即可顯著提升流暢度。本文為入門篇,精選 8 條基礎且高影響力的技巧,配合圖解與代碼範例,幫助開發者建立正確的效能意識。
// NSURLConnection 異步 (iOS 7+ 推薦)
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// 回到主執行緒更新 UI
dispatch_async(dispatch_get_main_queue(), ^{
[self updateUIWithData:data];
});
}];
// 第三方庫 (AFNetworking / Alamofire) 內部已處理執行緒切換
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 1. 後台執行緒:耗時操作 (解析、計算、讀寫檔案)
id result = [self performExpensiveComputation];
// 2. 切回主執行緒:更新 UI
dispatch_async(dispatch_get_main_queue(), ^{
[self updateUIWithResult:result];
});
});
為何雙層 dispatch_async? 外層切到背景佇列,內層切回主佇列 — 確保 UI 更新在主執行緒,符合 UIKit 單執行緒模型。
UIImageView 縮放圖片需 CPU 重新採樣,嵌入 UIScrollView 時每幀皆需縮放 → 嚴重掉幀imageView.image
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *original = [UIImage imageWithData:data];
UIImage *resized = [self resizeImage:original toSize:targetSize];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = resized;
});
});
| 集合類型 | 底層結構 | 查找 | 插入/刪除 | 有序性 | 適用場景 |
|---|---|---|---|---|---|
NSArray | 動態陣列 | 索引 O(1)、值 O(n) | O(n) (需移動元素) | 有序 | 有序列表、隨機訪問、小數據量 |
NSDictionary | 雜湊表 | 鍵 O(1) | O(1) 平均 | 無序 | 鍵值映射、快速查找、JSON 解析 |
NSSet | 雜湊集合 | 值 O(1) | O(1) 平均 | 無序、唯一 | 去重、成員檢測、交集/並集運算 |
NSOrderedSet | 雜湊+鏈表 | 值 O(1) | O(1) 平均 | 有序、唯一 | 需保持順序且去重的場景 |
建議:閱讀 Apple 官方 Collections Programming Topics 深入理解。
NSURLConnection / NSURLSession 預設自動處理 Accept-Encoding: gzip, deflate 並解壓
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad; // 優先緩存
retain/release/autorelease__weak)、CoreFoundation 對象 (需手動 CFRetain/CFRelease)、block 循環
static NSString *CellID = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID forIndexPath:indexPath];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
}
// 配置 cell 數據
cell.textLabel.text = items[indexPath.row];
return cell;
無 reuseIdentifier 後果:每行建立新 Cell → 記憶體暴漲、滾動嚴重掉幀、頻繁 GC/釋放開銷。
view.opaque = YES 告訴繪製系統無需混合底層像素,直接覆蓋Instruments → Core Animation → Color Blended Layers 檢測混合層 (紅色=混合、綠色=不透明)UIStoryboardReference 連接下篇將進階探討:離屏渲染優化、圖片解碼下沉、佈局計算緩存、啟動優化、Instruments 實戰分析等。