您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

解決 searchDisplayController 導致的陣列越界崩潰

編輯:iOS 相關教學

使用 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。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved