在NSArray中获取NSDictionary中的所有值

时间:2011-02-17 23:11:11

标签: iphone objective-c nsarray nsdictionary

我有一个充满NSDictionary对象的NSArray,每个NSDictionary里面都有一个唯一的ID。我想根据ID查找特定的词典,并在我自己的词典中获取该词典的所有信息。

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...)

我想得到第二个字典对象的名称和重量(我不知道对象的索引......如果只有两个dicts,我可以从[myArray objectAtIndex:1]创建一个字典)

所以,我知道数字149.我怎样才能将myArray中的第二个myDictionary对象变成一个新的NSDictionary?

2 个答案:

答案 0 :(得分:8)

作为雅各布答案的替代方案,你也可以让字典找到对象:

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

答案 1 :(得分:3)

您需要遍历NSDictionary中的每个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;
}
相关问题