[英]Filtering an array with large number of Items in Swift
我試圖通過過濾一個包含 3000 多個項目的數組來實現在 tableview 中的搜索,並且正如預期的那樣,結果是一個非常慢的搜索(在按下鍵幾秒鍾后,字母出現在搜索字段中)。 關於如何使搜索更快的任何建議?
我嘗試過使用filteredClips.filter { $0.text?.range(of: searchField.stringValue, options: [.caseInsensitive, .anchored ]) != nil }
但它的結果與下面的代碼相同。
func controlTextDidChange(_ obj: Notification) {
let searchText = searchField.stringValue.lowercased()
let searchResults = filteredClips.filter {($0.text?.lowercased().contains(searchText))!
|| ($0.desc != nil &&
($0.desc?.lowercased().contains(searchField.stringValue.lowercased()))!)}
filteredClips = searchResults
clipsTableView.reloadData()
}
注意:我認為上面提到的慢文本輸入是由於每次都等待controlTextDidChange
完成。 是否可以在不等待controlTextDidChange
完成每個字符的情況下繼續插入字符?
您應該使用文本字段委托並嘗試按用戶輸入的每個字符用戶進行搜索。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (searchText.text! as NSString).replacingCharacters(in: range, with: string)
let count = text.count
if count > 1
{
searchList = searchText.text!.isEmpty ? searchList : searchList.filter({(searchListTitle: searchListDataModel) -> Bool in
// If dataItem matches the searchText, return true to include it
return searchListTitle.title?.range(of: searchText.text!, options: .caseInsensitive) != nil
})
tableView.reloadData()
return true
} else {
tableViewList = searchList
tableView.reloadData()
return true
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.