Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 968
geerlingguy Avatar asked Feb 17 '11 23:02

geerlingguy


2 Answers

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];
like image 54
Chuck Avatar answered Sep 23 '22 20:09

Chuck


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;
}
like image 21
Jacob Relkin Avatar answered Sep 21 '22 20:09

Jacob Relkin