在Array Of Dictionaries中找到具有特定键值对的字典

时间:2013-10-08 08:58:10

标签: objective-c dictionary nsarray nsdictionary

我有一系列词典

for(int i = 0; i < 5; i++) {
    NSMutableDictionary *_myDictionary = [NSMutableDictionary dictionary];

    [_myDictionary setObject:[NSString stringWithFormat:@"%d",i] forKey:@"id"];
    [_myDictionary setObject:label.text @"Name"];
    [_myDictionary setObject:label1.text @"Contact"];
    [_myDictionary setObject:label2.text @"Gender"];
}

[_myArray addObject:_myDictionary];

现在我想从数组中选择一个字典,其objectForKey:@“id”是1或2或其他类似的东西,比如有一个sql查询从表中选择*,其中id = 2。 我知道这个过程

int index = [_myArray count];

for(int i = 0; i < 5; i++)
{

NSMutableDictionary *_myDictionary = [NSMutableDictionary dictionaryWithDictionary:[_myArray objectAtIndex:i]];

if([[_myDictionary objectForKey:@"id"] isEqualToString:id])
{

index = i;

return;

}

}

if(index != [_myArray count])
    NSLog(@"index found - %i",index);

else
    NSLog(@"index not found");

任何帮助将不胜感激。 在此先感谢!!!

2 个答案:

答案 0 :(得分:2)

试试这个,这是通过使用快速枚举

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for(dict in _myArray)
    {

        if([[dict valueForKey:@"id"] isEqualToString:@"1"])
        {
            return;
        }
    }

答案 1 :(得分:0)

您应该使用[NSNumber numberWithInteger: i]而不是NSString。

此搜索的代码应如下所示:

NSString *valueToFind = [NSString stringWithFormat:@"%d", intValue]; // [NSNumber numberWithInteger: intValue] 
NSInteger index = [_myArray indexOfObjectPassingTest:^BOOL(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
    return [valueToFind isEqualToString: [obj objectForKey: @"id"]];
}];
NSDitionary *found = [_myArray objectAtIndex: index];