我有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循环的情况下获取索引吗?
最佳答案
您可以像这样在category
上添加NSArray
(这也会进行类型安全检查;仅处理字典数组):
- (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];
}
关于ios - 查找存储在NSDictionary中的值的索引和存储在NSMutableArray中的NSDictionary的值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33143836/