使用NSDictionary对象从数组中获取对象

时间:2014-08-29 11:47:26

标签: ios objective-c arrays cocoa-touch nsdictionary

无论密钥是什么,我都需要能够显示对象值。或者使用对象键显示对象。

    NSMutableArray *array = [NSMutableArray array];
    NSMutableDictionary *dict= [[NSMutableDictionary alloc] init];

    [dict setObject:[NSNumber numberWithInt:10] forKey:@"key"];
    [array addObject:dict];

    NSLog(@"Key: %@", [[array objectAtIndex:0] key]);
    NSLog(@"Value: %@", [[array objectAtIndex:0] valueForKey:[[array objectAtIndex:0] key]]);

    //Both logs "[__NSDictionaryM key]: unrecognized selector sent to instance"

为什么这不起作用?我应该怎么做?

注意:在此示例中,keyValue是"键",但我不知道原始代码中的keyValue ..

2 个答案:

答案 0 :(得分:3)

NSMutableArray *array = [NSMutableArray array];

NSMutableDictionary *dict= [[NSMutableDictionary alloc] init];
[dict setObject:[NSNumber numberWithInt:10] forKey:@"key"];
[array addObject:dict];

尝试

NSDictionary *dict = [array objectAtIndex:0];
NSArray *values = [dict allValues];
NSArray *keys = [dict allKeys];

并记录

NSLog(@"Keys: %@", keys);
NSLog(@"Values: %@", values);

for (id key in keys) {

    NSLog(@"Value: %@ for Key: %@", [dict objectForKey:key], key);
}

答案 1 :(得分:1)

你可以这样做

for(NSDictionary *aDict in array)
    {
        for(NSString *aStrKey in aDict)
        {
            NSLog(@"%@", [aDict valueForKey:aStrKey]);
        }
    }