使用 UISearchDisplayController 時,如果設定了一行看似無害的分隔線樣式,卻在某些情境下直接崩潰,那大概就是我踩過的這個坑。
執行以下程式碼後 App 崩潰:
[searchDisplayController.searchResultsTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
錯誤訊息如下:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]' *** First throw call stack: ( 0 CoreFoundation 0x000000010c6c6c65 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x000000010c35fbb7 objc_exception_throw + 45 2 CoreFoundation 0x000000010c5bd17e -[__NSArrayI objectAtIndex:] + 190 3 UIKit 0x000000010d230fd2 -[UITableViewDataSource tableView:indentationLevelForRowAtIndexPath:] + 106 4 UIKit 0x000000010cdfb1b9 __53-[UITableView _configureCellForDisplay:forIndexPath:]_block_invoke + 1711 )
從堆疊中的第三行就能看出線索——崩潰發生在 tableView:indentationLevelForRowAtIndexPath::
3 UIKit 0x000000010d230fd2 -[UITableViewDataSource tableView:indentationLevelForRowAtIndexPath:] + 106
原因是:搜尋結果的資料源與主表單共用同一套 dataSource 方法,而搜尋結果的資料陣列此時可能只有 1 筆(或 0 筆),系統卻拿主表單的 index 去取值,於是就越界了。
手動實作 indentationLevelForRowAtIndexPath: 並固定回傳 0,讓系統不再去查那個有問題的陣列:
- (NSInteger)tableView:(UITableView *)tableView
indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 0;
}
這類「搜尋結果與主列表共用 dataSource」的崩潰還有幾個常見變形,例如 numberOfRowsInSection: 沒有依 tableView 參數分流、cellForRowAtIndexPath: 取用了錯誤的資料來源。根本的解法是在每一個 dataSource 方法開頭先判斷 tableView == self.searchDisplayController.searchResultsTableView,分別回傳對應的資料,而不是只補上一個 indentationLevel 的洞。另外,UISearchDisplayController 自 iOS 8 起已被標記為過時,新專案建議改用 UISearchController。