這是一份長年累積的問題排查筆記,內容涵蓋手勢事件、Auto Layout、UITableView、動畫、網路與工具鏈等面向。以下挑出仍具參考價值的部分重新分類整理,並標註哪些寫法在現代 iOS 上已經有更好的替代方案。
原因是事件傳遞鏈被中斷。若要在 scrollView 層級攔下 touch 並換算成子視圖座標,可以覆寫 touchesBegan:(用 Category 也可以,不一定要繼承):
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (!self.dragging) { // 拖曳中不處理點擊
UITouch *touch = [touches anyObject];
CGPoint loc = [touch locationInView:self];
// 把座標轉成子視圖的座標系
CoView *coView = (CoView *)[self viewWithTag:5267];
CGPoint newLoc = [coView convertPoint:loc fromView:self];
int col = newLoc.x / (kBtnWH + kBtnMarginH);
int row = newLoc.y / (kBtnWH + kBtnMarginV);
int i = row * kBtnColumnNum + col;
[[self nextResponder] touchesBegan:touches withEvent:event];
[coView btnTouched:i]; // coView 內要自行處理 i 越界
}
[super touchesBegan:touches withEvent:event];
}
現代替代方案:直接用 UITapGestureRecognizer 搭配 locationInView:,或乾脆用可點擊的子視圖,比覆寫 touch 事件好維護得多。
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
}
Category 無法合成 ivar,必須用關聯物件:
static void *MyObjectMyCustomPropertyKey = (void *)&MyObjectMyCustomPropertyKey;
@implementation MyObject (ExtendedProperties)
- (id)myCustomProperty {
return objc_getAssociatedObject(self, MyObjectMyCustomPropertyKey);
}
- (void)setMyCustomProperty:(id)value {
objc_setAssociatedObject(self, MyObjectMyCustomPropertyKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
NSTimer 沒有原生的 pause,但可以用「把 fireDate 推到遠方」的技巧:
@implementation NSTimer (Pause)
- (void)pause {
if (![self isValid]) return;
[self setFireDate:[NSDate distantFuture]]; // 推到遙遠的未來,等於暫停
}
- (void)resume {
if (![self isValid]) return;
[self setFireDate:[NSDate date]]; // 立刻恢復
}
@end
只要 constant 變了,就必須讓相關視圖重新布局,並包在動畫裡才有過渡效果:
_topView.bigImgHeightConstraint.constant = 0;
[UIView animateWithDuration:0.3 animations:^{
[self.view layoutIfNeeded];
[_topView layoutIfNeeded];
}];
weakcopyweak(避免循環引用)copystrongassign症狀是:用 xib + Auto Layout 建立的 footerView,首次進入時高度為 0,跳頁再回來就正常。原因是 tableView 的自身布局尚未完成,footerView 拿不到正確的約束解。筆記中的解法是延遲一點點再設定:
self.tableView.tableHeaderView = self.headView;
_footerView = [RowView RowView];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
strongSelf.tableView.tableFooterView = _footerView;
[strongSelf.tableView layoutIfNeeded];
});
更根本的解法:改用 tableFooterView 的 Auto Layout 自撐高度(iOS 9 之後搭配 UITableViewAutomaticDimension),或延遲到 viewDidLayoutSubviews 中設定,比用固定秒數的 dispatch_after 可靠。
幾乎都是 xib 中拖過的連線沒有清乾淨。檢查 xib 的 Connections 面板,刪掉那些殘留的 outlet 即可。
// viewDidLoad tableView.rowHeight = UITableViewAutomaticDimension; tableView.estimatedRowHeight = 10; // cellForRow 中 [cell layoutIfNeeded];
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
實作 commitEditingStyle:forRowAtIndexPath:(哪怕內容是空的)就會出現刪除按鈕。順序很重要——先刪資料來源,再刪 row:
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
[blockSelf.arrayData removeObjectAtIndex:indexPath.row]; // 1. 先改資料
[blockSelf.tableView deleteRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic]; // 2. 再刪畫面
}
// 一路往上找到 table view
UITableView *tableView = (UITableView *)cell;
while (![tableView isKindOfClass:[UITableView class]]) {
tableView = (UITableView *)[tableView superview];
}
NSIndexPath *path = [tableView indexPathForCell:cell];
row = path.row;
用 CAKeyframeAnimation 對 transform 做縮放關鍵影格,做出「從小放大、略微超出再收住」的回彈感。注意要在 viewDidAppear 之後呼叫,視圖已在層級中才看得到效果。
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; animation.duration = 0.5; animation.delegate = self; animation.removedOnCompletion = YES; animation.fillMode = kCAFillModeForwards; NSMutableArray *values = [NSMutableArray array]; [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]]; [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]]; [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]]; [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]]; animation.values = values; [_contentView.layer addAnimation:animation forKey:nil];
[SVProgressHUD showSuccessWithStatus:@"提交成功"];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
[blockSelf.navigationController popViewControllerAnimated:YES];
});
這是處理階層式清單的通用套路:先用 NSSortDescriptor 依分組鍵排序,遍歷時把相鄰同組的項目收攏成子陣列,最後在每組內依顯示順序排序。這樣做的關鍵洞察是:分組只有在資料已排序時才能用「相鄰比較」一次掃描完成,不必用字典做 O(n²) 的查找。
SELECT max(FTime), * FROM DynamicInfoTable WHERE FUID = '...' GROUP BY FOrgID, FType ORDER BY max(FTime) DESC
寫法上要注意:ORDER BY 必須用聚合表達式 max(FTime) 而不是裸欄位,否則排序結果會與分組結果不一致。
NSData *data = [NSJSONSerialization dataWithJSONObject:content
options:NSJSONWritingPrettyPrinted
error:nil];
self.jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
若 options 用 NSJSONWritingPrettyPrinted,輸出的字串會帶換行與縮排,放到某些不解析空白的後端時可能出問題;反之若資料要嵌進 HTML 或 JS,也別忘了 NSJSONReadingMutableLeaves 之類的選項是讀取端用的,寫另一端別搞混。
這個錯誤來自伺服器端而非 iOS。從回應標頭可以明確看到 Allow = GET,代表該端點不接受 POST。解法只有兩種:改呼叫端改用 GET,或請後端開放 POST。在 iOS 端反覆嘗試是徒然的。
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]]) {
NSLog(@"已安裝微信");
}
iOS 9 之後,canOpenURL: 必須先在 Info.plist 的 LSApplicationQueriesSchemes 中宣告 scheme,否則一律回傳 NO。
同一個 URL 若內容會變(例如動態生成的圖),SDWebImage 預設會永久快取導致圖片不更新。解法是改用記憶體快取,或幫 URL 加上版本參數:
[imgView sd_setImageWithURL:url
placeholderImage:imgPlace
options:SDWebImageCacheMemoryOnly];
策略是先查快取,再判斷網路型別:WiFi 直接抓;蜂窩網路則要看使用者是否開啟了「行動網路自動下載」設定。
SDWebImageManager *manager = [SDWebImageManager sharedManager];
if ([manager cachedImageExistsForURL:url]) { /* 直接用快取 */ return; }
if ([[KLNetworkStatus sharedKLNetworkStatus] isReachableViaWifi]) { /* 下載 */ return; }
if ([[KLNetworkStatus sharedKLNetworkStatus] isReachableViaWWAN]) {
if ([KLTools isNetworkDownloadSet]) { /* 依使用者設定決定 */ }
}
原因是在 inDatabase: 的 block 內部又呼叫了 inDatabase:。同一個序列佇列中,前一個 block 必須等後一個完成才能出隊,而後一個又必須等前一個出隊才能執行——直接死鎖。解法很簡單:不要在 inDatabase: 的 block 裡再呼叫 inDatabase:。
用 assign 或 weak 修飾 NSNumber 屬性時,物件可能被提前釋放而變成懸垂指標。物件型別一律用 strong:
@property (nonatomic, strong) NSNumber *orderPrice;
到 Targets → Build Settings → Code Signing → Provisioning Profile,把指向不存在 UUID 的設定改成正確的描述檔(或讓 Xcode 自動重新下載)。切勿讓 Xcode 自行 revoke 憑證——那會讓團隊中與該憑證關聯的所有描述檔一起失效。正確作法是向團隊成員索取描述檔,雙擊匯入後在設定中選擇它。
通常是 Xcode 版本低於裝置系統版本。例如 Xcode 6.0.1 無法為 iOS 8.1 的裝置建置,需升級 Xcode。另一種可能是 Target 的 iOS Deployment Target 設得比裝置系統高,調低即可。
若在模擬器上播放影片時出現 rtcreporting 相關的崩潰,將全域例外斷點關掉即可,這屬於工具鏈層級的 bug,不是程式問題。
先檢查是否誤開了控制中心中的「直排方向鎖定」。程式面則要確認有實作 supportedInterfaceOrientationsForWindow: 與各頁面的 supportedInterfaceOrientations,並注意 shouldAutorotateToInterfaceOrientation: 在 iOS 6 之後已被取代。
git init
NSString *regex = @"[一-龥]{2,8}"; 搭配 NSPredicate 的 SELF MATCHES。NSRange r = [str rangeOfString:@"xxx"]; if (r.location != NSNotFound) { ... }webViewDidFinishLoad: 中用 sizeThatFits:CGSizeZero,或用 JS 取 document.body.offsetHeight。NSMakeRange(loc, len) 建立,不是物件。FilterCtrl *FilterCtrl = ... 會讓編譯器把右邊誤判為型別宣告而報錯。@"main" 中的 \ 是轉義字元,要表示真正的反斜線需寫成 @"main\\";除錯視窗中顯示成兩個是顯示層的問題。這批筆記成形於 iOS 7~8 的時代,其中不少 API 已被取代。若在新專案中沿用,建議先做以下替換:
| 舊寫法 | 建議改用 |
|---|---|
| UIAlertView / UIActionSheet | UIAlertController |
| UIWebView | WKWebView |
| shouldAutorotateToInterfaceOrientation: | supportedInterfaceOrientations |
| NSKeyedUnarchiver unarchiveObjectWithData: | unarchivedObjectOfClass:fromData:error: |
| stringByAddingPercentEscapesUsingEncoding: | stringByAddingPercentEncodingWithAllowedCharacters: |
| 手動呼叫 release(MRC) | ARC 下直接省略 |
保留這份筆記的價值,在於其中的排查思路:先看現象、再定位到系統元件、最後找出根本原因——這個流程不因 API 更迭而改變。