查找存储在 NSDictionary 中的值的索引和存储在 NSMutableArray 中的 NSDictionary

Find index of value which is stored into NSDictionary and NSDictionary stored into NSMutableArray

我有 NSMutableArray 存储 NSDictionary。考虑以下包含 NSDictionary.

的数组
<__NSArrayM 0x7f9614847e60>(
{
    "PARAMETER_KEY" = 1;
    "PARAMETER_VALUE" = ALL;
},
{
    "PARAMETER_KEY" = 2;
    "PARAMETER_VALUE" = ABC;
},
{
    "PARAMETER_KEY" = 3;
    "PARAMETER_VALUE" = DEF;
},
{
    "PARAMETER_KEY" = 4;
    "PARAMETER_VALUE" = GHI;
},
{
    "PARAMETER_KEY" = 5;
    "PARAMETER_VALUE" = JKL;
}
)

我可以使用以下代码找到特定 NSDictionary 的索引。

int tag = (int)[listArray indexOfObject:dictionary];

但是如果我有 PARAMETER_VALUE = GHI 并使用这个值,我想找到数组中的字典索引。我不想使用 for 循环。我可以不用for循环获取索引吗?

您可以将 NSPredicate 用于此目的:

// Creating predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.PARAMETER_VALUE MATCHES %@",@"GHI"];

// Filtering array
NSArray *filteredArr   = [arr filteredArrayUsingPredicate:predicate];

// If filtered array count is greater than zero (that means specified object is available in the array), checking the index of object
// There can be multiple objects available in the filtered array based on the value it holds (In this sample code, only checking the index of first object
if ([filteredArr count])
{
    NSLog(@"Index %d",[arr indexOfObject:filteredArr[0]]);
}

嗯,必须用一种方式来列举。从字面上理解你的要求(没有 for 循环),你可以使用快速枚举。但是,该任务可以 运行 并发,因为您只需要读取权限:

__block NSUInteger index;
[array enumerateObjectsWithOptions: NSEnumerationConcurrent
                     usingBlock:
^(NSDictionary *obj, NSUInteger idx, BOOL *stop)
{
  if( [obj valueForKey:@"PARAMETER_VALUE" isEqualToString:@"GHI" )
  {
    index = idx;
    *stop=YES;
  }
}

您可以像这样在 NSArray 上添加 category(这也会进行类型安全检查;仅处理字典数组):

- (NSInteger)indexOfDictionaryWithKey:(NSString *)iKey andValue:(id)iValue {
    NSUInteger index = [self indexOfObjectPassingTest:^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop) {
        if (![dict isKindOfClass:[NSDictionary class]]) {
            *stop = YES;
            return false;
        }

        return [dict[iKey] isEqual:iValue];
    }];

    return index;
}

然后只需直接在您的数组对象上调用 indexOfDictionaryWithKey:andValue: 即可获取索引。

以防万一,如果您想从该数组中获取字典对象,请在 NSArray 中再添加一个类别:

- (NSDictionary *)dictionaryWithKey:(NSString *)iKey andValue:(id)iValue {
    NSUInteger index = [self indexOfDictionaryWithKey:iKey andValue:iValue];

    return (index == NSNotFound) ? nil : self[index];
}

您可以使用 indexOfObjectPassingTest 方法 NSArray:

[listArray indexOfObjectPassingTest:^BOOL(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        return [dic[@"PARAMETER_VALUE"] isEqualToString:@"GHI"];
}];

此外,如果您可以拥有多个具有相同 PARAMETER_VALUE

的词典,请考虑使用 indexesOfObjectsPassingTest