获取 NSArray 内 NSDictionary 中的所有值

发布于 2024-10-17 23:36:33 字数 535 浏览 3 评论 0原文

我有一个充满 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...)

我想获取第二个字典对象的名称和权重(我不知道该对象的索引...如果只有两个字典,我可以从 [myArray objectAtIndex 制作一个字典:1])

那么,假设我知道数字 149。我如何才能将 myArray 中的第二个 myDictionary 对象放入新的 NSDictionary 中?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦旅人picnic 2024-10-24 23:36:33

作为雅各布答案的替代方案,您也可以直接要求字典查找该对象:

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

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];
陈年往事 2024-10-24 23:36:33

您需要遍历 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;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文