简体   繁体   English

过滤 Swift 中包含大量项目的数组

[英]Filtering an array with large number of Items in Swift

I'm trying to implement search in a tableview by filter an array with more than 3000 items, and as expected the result is a very slow search(The letters appear in the search field seconds after the key is pressed).我试图通过过滤一个包含 3000 多个项目的数组来实现在 tableview 中的搜索,并且正如预期的那样,结果是一个非常慢的搜索(在按下键几秒钟后,字母出现在搜索字段中)。 Any suggestions on how to make search faster?关于如何使搜索更快的任何建议?

I've tried using filteredClips.filter { $0.text?.range(of: searchField.stringValue, options: [.caseInsensitive, .anchored ]) != nil } but its the same result as the code below.我尝试过使用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()
}

Note: I think the slow text typing mentioned above is due wait for controlTextDidChange to complete every time.注意:我认为上面提到的慢文本输入是由于每次都等待controlTextDidChange完成。 Is it possible to continue character insertion without waiting for controlTextDidChange to complete for each character?是否可以在不等待controlTextDidChange完成每个字符的情况下继续插入字符?

You should use textfield delegate and try search by each character user entered by user.您应该使用文本字段委托并尝试按用户输入的每个字符用户进行搜索。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM