简体   繁体   中英

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). 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.

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. Is it possible to continue character insertion without waiting for controlTextDidChange to complete for each character?

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
        }
        
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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