【问题标题】:NSArray full of NSDictionaries. How to find index of object?NSArray 充满了 NSDictionaries。如何找到对象的索引?
【发布时间】:2024-05-20 22:30:02
【问题描述】:

我有一个array,里面填满了NSDictionaries。我想找到其中一本字典的index,但我对这本字典的了解只是value 的键@"name". 我该怎么做 ?

【问题讨论】:

    标签: iphone objective-c ios xcode nsarray


    【解决方案1】:
     NSArray *temp = [allList valueForKey:@"Name"];
     NSInteger indexValue = [temp indexOfObject:YourText];
     NSString *name = [[allList objectAtIndex:indexValue] valueForKey:@"Name"]  
    

    【讨论】:

      【解决方案2】:

      theArray 中查找@"name" 的值为theValue 的第一个字典的索引:

      NSUInteger index = [theArray indexOfObjectPassingTest:
              ^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop)
              {
                  return [[dict objectForKey:@"name"] isEqual:theValue];
              }
      ];
      

      如果没有找到匹配的对象,index 将是 NSNotFound

      【讨论】:

      • 我猜 NSPredicate 是要使用的东西。
      • @Ashishail:谓词用于过滤数组,即返回一个包含所有符合条件的对象的新数组。如果只需要第一个匹配的索引,我认为indexOfObjectPassingTest更有效。
      • @SmartTree: 2147483647 = 0x7FFFFFFF 是NSNotFound
      • @Rambatino:此方法确实在找到匹配项后立即停止迭代。该块可以将 stop 参数设置为 NO 以提前停止迭代,在这种情况下,该方法将返回 NSNotFound。例如,如果在前 1000 个元素中找不到匹配项,您可以停止迭代。 – 这能回答你的问题吗?
      • 完美。感谢您提供优雅简单的解决方案!