简体   繁体   中英

NSDictionary get objects by property value

I have NSDictionary which contains following type of objects.

OBJECT1 - isFree:NO
          Name: Papaya

OBJECT2 - isFree:YES
          Name: Apple

OBJECT3 - isFree:YES
          Name: Grapes

I can get object for the given key by using objectForKey as follows.

NSString* contentId = @"OBJECT3";
ACBContentType *object = [[[ACBLibrary sharedLibrary] contentsDictionary] objectForKey:contentId];

However I want to get all the objects which isFree:YES by reading object isFree property. What is the best way to do this?

If you are not interested in the keys, but solely the objects, it is pretty simply:

NSDictionary *contentDictionary = …;
NSPredicate *freePredicate = [NSPredicate predicateWithFormat:@"isFree == %@", @YES];
NSArray* freeContent = [[contentDictionary allValues] filteredArrayUsingPredicate:freePredicate];

Typed in Safari.

-allValues returns an array of all value objects. -filteredArrayUsingPredicate: reduces this to the items fulfilling the predicate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM