1

I'm trying to get an array of keys where the value for the corresponding key in an NSDictionary is @YES.

For EG,: Starting Dictionary:

NSDictionary* dict = @{@"key1" : @YES, @"key2": @YES, @"key3": @NO, @"key4": @NO};

Desired Result:

NSArray* array = @[@"key1", @"key2"];

I tried doing this with NSPredicates and subpredicates but couldn't find one that did what i wanted. My "working" but ugly solution is:

NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:0];
NSDictionary* dict = @{@"key1" : @YES, @"key2": @YES, @"key3": @NO, @"key4": @NO};
for (NSString* key in [dict allKeys]) {
    if ([[dict objectForKey:key] isEqualToNumber:@YES])
        [array addObject:key];
}

What is a better way of doing this, possibly with NSPredicates?.

sathiamoorthy
  • 1,488
  • 1
  • 13
  • 23
SimpsOff
  • 252
  • 3
  • 10

1 Answers1

6

This kind of abstracts a lot of the messiness away

NSArray *results = [dict keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) {
  return [obj isEqualToNumber:@YES];
}].allObjects;

NSLog(@"%@", results);
Paul.s
  • 38,494
  • 5
  • 70
  • 88