gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:29:43 27 4
gpt4 key购买 nike

我有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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com