1

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)

Andy Jacobs
  • 15,187
  • 13
  • 60
  • 91
  • Could you show us how you're initializing your array? are you sure you have what you think in the `array` variable? – Goles Jan 02 '13 at 15:11
  • You can do this, but it's going to be tricky. Dave DeLong gave the answer here: http://stackoverflow.com/a/4831366/312312 – Lefteris Jan 02 '13 at 15:14

2 Answers2

4
NSString* text = @"mac" ;
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"any data contains[cd] %@",text] ;
NSArray* filteredArray = [theArray filteredArrayUsingPredicate:predicate] ;
John Sauer
  • 4,411
  • 1
  • 25
  • 33
2

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.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235