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 t开发者_JAVA百科he 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;
}
精彩评论