查找值的索引存储在NSDictionary中NSDictionary存储在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循环,我能得到index吗?

您可以使用NSArrayindexOfObjectPassingTest方法:

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

另外,如果您可以使用多个具有相同PARAMETER_VALUE的字典,请考虑使用indexesOfObjectsPassingTest

您可以像这样在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];
}

您可以使用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;
  }
}

最新更新