Predicate to filter array of strings in SWIFT throws error saying NSCFString is not key-value coding

独自空忆成欢 提交于 2019-12-10 04:24:37

问题


Below is my code snippet

//Search Bar Delegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String)
{
    println(searchText)
    var predicate:NSPredicate=NSPredicate(format: "SELF CONTAINS[c] \(searchText)")!
    self.listItemToBeDisplayed=listItem.filteredArrayUsingPredicate(predicate)
    (self.view.viewWithTag(1) as UITableView).reloadData()

}

Error I got:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x17405ef90> valueForUndefinedKey:]: this class is not key value coding-compliant for the key V.'

I want to filter strings in array to be filtered by my search string. If my search string is contained in any of the string in array, then it should be listed.


回答1:


NSPredicate(format:) strongly expects to be used with printf-style format strings (it automatically quotes arguments as it inserts them, etc).

You're using Swift's string interpolation, so the already-formatted query comes to NSPredicate as a single string. That keeps it from doing whatever voodoo it does with arguments, leaving you with a malformed query.

Use printf-style formatting instead:

if let predicate = NSPredicate(format: "SELF CONTAINS %@", searchText) {
    self.listItemToBeDisplayed = (listItem as NSArray).filteredArrayUsingPredicate(predicate)
    (self.view.viewWithTag(1) as UITableView).reloadData()
}



回答2:


Working with predicate for pretty long time. Here is my conclusion (SWIFT)

//Customizable! (for me was just important if at least one)
request.fetchLimit = 1


//IF IS EQUAL

//1 OBJECT
request.predicate = NSPredicate(format: "name = %@", txtFieldName.text)

//ARRAY
request.predicate = NSPredicate(format: "name = %@ AND nickName = %@", argumentArray: [name, nickname])


// IF CONTAINS

//1 OBJECT
request.predicate = NSPredicate(format: "name contains[c] %@", txtFieldName.text)

//ARRAY
request.predicate = NSPredicate(format: "name contains[c] %@ AND nickName contains[c] %@", argumentArray: [name, nickname])


来源:https://stackoverflow.com/questions/26920600/predicate-to-filter-array-of-strings-in-swift-throws-error-saying-nscfstring-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!