在Objective-C中获取字典数组中的特定对象

时间:2013-06-22 13:49:01

标签: objective-c arrays dictionary nsarray nsdictionary

我有一个字典数组,我想获取包含我正在搜索的键的数组的值。

例如,我有一个名为locationArray的数组:

(
    {
    id = 1,
    info = 
        {
        name = "Person1";
        address = "Chicago";
        };
    };
    id = 2,
    info = 
        {
        name = "Person2";
        address = "Chicago";
        };
    };
    id = 3,
    info = 
        {
        name = "Person3";
        address = "New York";
        };
    };
);

我希望在芝加哥找到一个有地址的人。结果(chicagoArray)将是这样的:

(
    {
    id = 1,
    info = 
        {
        name = "Person1";
        address = "Chicago";
        };
    };
    id = 2,
    info = 
        {
        name = "Person2";
        address = "Chicago";
        };
    };
);

我做了这个循环,但我不知道该怎么做我的resultArray:

for (id result in locationArray)
{
     if ([[result valueForKeyPath@"info.address"] isEqualToString:@"Chicago"])
     {
         // What to do inside the resultArray?
         // NSArray *resultArray = [[NSArray alloc] initWithObjects:@""];
     }
}

我该怎么做?谢谢!

2 个答案:

答案 0 :(得分:3)

NSMutableArray* entries= [NSMutableArray array];
for(NSDictionary* dict in array)
{
    NSDictionary* innerDict= dict[@"info"];
    if([innerDict[@"address"] isEqualToString: @"Chicago"])
    {
        [entries addObject: dict];
    }
}

答案 1 :(得分:1)

您的数组包含NSDictionary

您可以迭代并检查条件,如果满足则将该对象添加到新数组。