shifu shifu - 3 months ago 21
iOS Question

How to filter NSArray using predicate on an object property

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
[self.map removeAnnotations:self.map.annotations];
if ([textField isEqual:self.searchText]) {
NSPredicate *bPredicate =
[NSPredicate predicateWithFormat:@"name contains[c], %@",self.searchText.text];

self.filteredArray = [self.hotelArray filteredArrayUsingPredicate:bPredicate];
NSLog(@" HEARE %@",self.filteredArray);
[self markAllHotels];
}
return YES;
}


hotelArray
and
filteredArray
are
NSArray
s.

hotelArray
has objects of type
hotel
where
hotel
has a property
name
.

Problem :
I want to filter
hotelArray
according to
hotel.name
when
hotel.name
matches text entered in
searchText
[text field], but I am getting an empty
self.filteredArray
.

Answer

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)

Alternate using swift filter

var searchText = "Galaxy"

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