2013-10-17 81 views

回答

-1

我找到了答案。我已經嘗試了下面的代碼,但它提供了所有的數據。 因爲我得到的json是worng格式。

for (NSString *key in Dict) {} 
+0

'NSDictionary'中的鍵不必是'NSString'類型,因爲在你的例子中鍵將會是'NSNumbers' – rckoenes

1

試試這個方法...

獲取所有按鍵

NSArray *a=[yourDictionary allKeys]; 
0
NSArray *keys = [dictionary allKeys]; 

試試這個。您將獲得數組中的所有密鑰。然後你可以相應地在NSString

3

您環路直通的NSDictionary鍵:

NSArray *keys = [dictionary allKey]; 

for (id *key in keys) { 
    NSDictionary *userPhoto = [dictionary objectForKey:key]; 
    // here you can either parse the object to a custom class 
    // or just add it to an array. 
} 
直接在 NSDictionary

或者使用fast enumeration

for (id *key in dictionary) { 
    NSDictionary *userPhoto = [dictionary objectForKey:key]; 
    // here you can either parse the object to a custom class 
    // or just add it to an array. 
} 

每鍵可以檢索對象。

或使用enumerateKeysAndObjectsUsingBlock:

[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 
    // Here you can access the object and key directly. 
} 
+0

+1爲漂亮的解釋:) –

+1

*「有循環通一的NSDictionary沒有真正的方法」 * - 這是不正確的。 'for(NSString * key in dict)'* *列舉字典鍵,所以你不需要'allKeys'。並且有'enumerateKeysAndObjectsUsingBlock:'... –

+0

@MartinR你是對的,它也會通過鍵循環 – rckoenes

0

另一種方法是使用enumerateKeysAndObjectsUsingBlock: API來枚舉密鑰和對象,

用法很簡單,

[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { 
    NSLog(@"Key: %@, Value:%@",key,obj); 
    if([key isEqualToString:@"0001"]) { 
     //Do something 
    } 
    // etc. 
}]; 

希望幫助!