Andy Jacobs
Andy Jacobs

Reputation: 15245

NSPredicate of NSArray in NSDictionary

My Array

(
   {id:1,data:(@"macbook",@"mac mini")},
   {id:2,data:(@"ipad",@"ipod")},
   {id:3,data:(@"macbook",@"ipod")}
)

I have a predicate

NSString *text = @"mac";
[NSPredicate predicateWithFormat:@"(data contains[cd] %@)",text];
[array filteredArrayUsingPredicate:predicate];

but it doesn't loop over my array inside my dictionary (my result should be an array containing 2 objects with id 1 and 3)

Upvotes: 1

Views: 871

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108159

I personally find NSPredicate formats very error prone.

You may consider using a block in order to filter your NSArray

NSString * filterString = @"mac";
NSIndexSet * indexes = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    NSArray * entry = obj[@"data"];
    for (NSString * value in entry)
        if ([value rangeOfString:filterString].location != NSNotFound)
            return YES;
    return NO;
}];
NSArray * filteredArray = [array objectsAtIndexes:indexes];

It's definitely longer and more verbose, but I find it definitely easier to read and debug.

Upvotes: 2

John Sauer
John Sauer

Reputation: 4421

NSString* text = @"mac" ;
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"any data contains[cd] %@",text] ;
NSArray* filteredArray = [theArray filteredArrayUsingPredicate:predicate] ;

Upvotes: 4

Related Questions