简体   繁体   中英

Grab all values in NSDictionary inside an NSArray

I have an NSArray full of NSDictionary objects, and each NSDictionary has a unique ID inside. I want to do lookups of particular dictionaries based on the ID, and get all the information for that dictionary in my own dictionary.

myArray contains:

[index 0] myDictionary object
  name = apple,
  weight = 1 pound,
  number = 294,

[index 1] myDictionary object
  name = pear,
  weight = .5 pound,
  number = 149,

[index 3] myDictionary object (etc...)

I want to get the name and weight for the second dictionary object (I won't know the index of the object... if there were only two dicts, I could just make a dictionary from [myArray objectAtIndex:1] )

So, say I know the number 149. How would I be able to get the second myDictionary object out of myArray into a new NSDictionary?

As an alternative to Jacob's answer, you could also just ask the dictionary to find the object:

NSPredicate *finder = [NSPredicate predicateWithFormat:@"number = 149"];
NSDictionary *targetDictionary = [[array filteredArrayUsingPredicate:finder] lastObject];

You'd need to iterate through every NSDictionary object in your NSArray :

- (NSDictionary *) findDictByNumber:(NSInteger) num {
   for(NSDictionary *dict in myArray) {
     if([[dict objectForKey:@"number"] intValue] == num) 
        return [NSDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:@"weight"], @"weight", [dict objectForKey:@"name"], @"name", nil];
   }
   return nil;
}

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