kb920 kb920 - 5 months ago 28
iOS Question

NSPredicate for exact match

NSArray *arrData = [NSArray arrayWithObjects:
@"cloud,country,plant",
@"country,cloud,plant",
@"country,plant,cloud",
@"clouds,country,plant"
,@"country,clouds,plant",
nil];


From above NSArray, I want objects which having a word "cloud"

I tried below code

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(self beginswith %@ OR self contains[CD] %@)",@"cloud",@",cloud"];
NSArray *arrResult = [arrData filteredArrayUsingPredicate:predicate];


But it's giving all 5 objects in arrResult. But I need only 3 (0,1,2) objects.

Answer

Try:

 NSPredicate* predicate = [NSPredicate predicateWithBlock:^(NSString* string, NSDictionary* options){

    NSArray* array = [string componentsSeparatedByString:@","];

    return [array containsObject:@"cloud"];

}];
Comments