[英]Grab all values in NSDictionary inside an NSArray
I have an NSArray full of NSDictionary objects, and each NSDictionary has a unique ID inside. 我有一个NSArray充满了NSDictionary对象,每个NSDictionary里面都有一个唯一的ID。 I want to do lookups of particular dictionaries based on the ID, and get all the information for that dictionary in my own dictionary. 我想根据ID查找特定字典,并在我自己的字典中获取该字典的所有信息。
myArray contains: myArray包含:
[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]
) 我想获得第二个字典对象的名称和重量(我不知道对象的索引...如果只有两个dicts,我可以从[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? 所以,比方说我知道数字149.我怎样才能将myArray中的第二个myDictionary对象变成一个新的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
: 您需要遍历NSArray
每个NSDictionary
对象:
- (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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.