The predicate for filtering an array of strings in SWIFT raises an error because NSCFString is not a key value

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:

*** Application termination due to the uncaught exception "NSUnknownKeyException", reason: '[<__NSCFString 0x17405ef90> valueForUndefinedKey:]: this class is not a key value compatible with the encoding for key V.'

I want to filter the rows in an array that will be filtered by my search string. If my search string is contained in any string in the array, it should be specified.

+6
source share
2 answers

NSPredicate(format:) relies heavily on the use of printf format with strings (it automatically quotes arguments when they are inserted, etc.).

Swift string interpolation is used, so an already formatted query comes to NSPredicate as a single string. This prevents you from doing something like voodoo with arguments, leaving you with a malformed request.

Instead, use printf formatting:

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

Working with a predicate for quite some 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]) 
0
source

Source: https://habr.com/ru/post/978167/


All Articles