您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

searchDisplayController 導致的陣列越界崩潰怎麼修

編輯:iOS 開發綜合

在設定 UISearchDisplayController 的結果列表分隔線樣式時,程式意外崩潰。以下記錄排查過程與解法。

出問題的那行程式碼是:

[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: 這個委派方法上。UISearchDisplayController 在配置 cell 時會回頭詢問縮排層級,而它內部維護的某個陣列此時只有一個元素,卻被索取索引 1,於是拋出 NSRangeException。

解法:自行實作縮排層級委派

既然問題出在系統預設實作取值越界,最直接的處理方式就是自己實作這個方法,固定回傳 0:

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 0;
}

這樣一來,系統不再走它那段有問題的預設邏輯,越界自然消失。若你的專案本來就需要多層縮排的視覺效果,也可以在這個方法裡依 indexPath 自行計算回傳值。

順帶一提,UISearchDisplayController 已被蘋果標記為不建議使用,新專案建議改用 UISearchController 搭配 UISearchResultsUpdating,能少掉不少這類歷史包袱帶來的坑。

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