1
votes

I have the following json object is stored as self.pElements. I have a search bar to be used to filter items based on the name.

[
 {"id":"1","name":"Baked Chicken","category":"1","price":"5.49"},
 {"id":"2","name":"Beef Kabob","category":"2","price":"5.49"},
 {"id":"3","name":"Beef Gyro","category":"1","price":"5.49"},
 {"id":"4","name":"Lamb Gyro","category":"4","price":"5.49"} 
] 

I try to filter by name as follows, but it always returns me null. even I type just Beef, nothing has been returned

pTempElements =[[NSMutableArray alloc] initWithArray:[self.pElements filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = %@", self.searchBar.text]]];
1
None of the "name" values are equal to "Beef". - rmaddy
name = => it means a "perfect match". you may want to replace it with name BEGINSWITH[c] (the [c] being for case insenstive in order to "beef" be okay. - Larme
could you please give a small example? What if user types Gyro only? - casillas
@hotspring Do you want show the names that contains Gyro only? - Dipankar Das

1 Answers

1
votes

If you want to filter for strings that contain the search string, use contains[cd]:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", searchText];

For list of the sorts of string comparisons one can do, see Predicate Format String Syntax: String Comparisons in the Predicate Programming Guide.