2014-08-29 79 views
0

無論密鑰是什麼,我都需要能夠顯示對象值。或者用對象鍵顯示一個對象。使用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 ..

+0

'[陣列objectAtIndex:0] ObjectForKey:@ 「鑰匙」];' – 2014-08-29 11:50:33

+0

查看更新後的問題 – Peter 2014-08-29 11:52:23

+1

'[陣列objectAtIndex:0] allKeys]。 '它將返回NSArray與該字典的所有鍵。 – 2014-08-29 11:53:12

回答

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

你可以這樣做

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