-1

我有一系列字典

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 查询 Select * from Table where 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");

任何帮助,将不胜感激。提前致谢 !!!

4

2 回答 2

2

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

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

        if([[dict valueForKey:@"id"] isEqualToString:@"1"])
        {
            return;
        }
    }
于 2013-10-08T09:47:23.110 回答
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];
于 2013-10-08T09:14:26.610 回答