问题
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