How to filter NSArray using predicate on an object property How to filter NSArray using predicate on an object property ios ios

How to filter NSArray using predicate on an object property


Try following lines, and make sure properyName is case sensitive. and you have placed , in predicate format, thats why its not working. just replace your code with following.

Objective C

NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF.name contains[cd] %@",self.searchText.text];self.filteredArray = [self.hotelArray filteredArrayUsingPredicate:bPredicate];NSLog(@"HERE %@",self.filteredArray);

Swift

var bPredicate: NSPredicate = NSPredicate(format: "SELF.name contains[cd] %@", self.searchText.text)self.filteredArray = self.hotelArray.filteredArrayUsingPredicate(bPredicate)NSLog("HERE %@", self.filteredArray)

Using swift filter

var searchText = "Galaxy"let filteredArray = hotelArray.filter { $0["name"] == searchText }print("** Result ** \n\(filteredArray)")

Swift 3.0

let arrEmp = [["name": "James", "age" : 27, "city" : "New york"],                   ["name": "Johnson", "age" : 24, "city" : "London"],                   ["name": "Alex", "age" : 28, "city" : "Newark"],                   ["name": "Mark", "age" : 25, "city" : "Paris"],                   ["name": "Steve", "age" : 25, "city" : "Silicon Valley"],                   ["name": "Lary", "age" : 28, "city" : "New york"]]// *** Filter by Name exact match ***var filterByName = arrEmp.filter { $0["name"] == "Mark" }print("filterByName \(filterByName)")// *** Filter by Age ***var filterByAge = arrEmp.filter { $0["age"] as! Int >  25 }print("filterByAge \(filterByAge)")

Swift 4.0

var filterByName = arrEmp.filterdo {    $0["name"] == "Mark"}print("filterByName filterByName)")var filterByAge = arrEmp.filterdo {    $0["age"] as! Int > 25}print("filterByAge filterByAge)")


Based on your information, this is your situation:

self.hotelArray      // Array in which we perform a searchself.filteredArray   // Result arrayname                 // Property of the object used for the predicate

This predicate should work for you:

NSString *searchText = self.searchText.text;NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.name contains[c] %@", searchText];self.filteredArray = [self.hotelArray filteredArrayUsingPredicate:predicate];


This is the predicate method that might work for you.

-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{    [filteredContactArray removeAllObjects];    NSArray *tempArray = [hotelArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name contains[c] %@ OR name contains[cd] %@",searchText]];    filteredArray = [NSMutableArray arrayWithArray:tempArray];//if you want the filtered array to be mutable or tempArray will work as as desired by you.}

contains[c]- means the predicate with case sensitive.contains[cd]- case insensitive string