Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 288
user1325792 Avatar asked Nov 13 '14 23:11

user1325792


1 Answers

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()
}
like image 106
rickster Avatar answered Sep 27 '22 17:09

rickster