遍历一个NSMutable字典只返回最后一个项目

问题描述:

//loop over alphabet and set the key values for addressbook 
for(char a = 'a'; a <= 'z'; a++){ 
     addressbook=[[NSMutableDictionary alloc] init]; 
     [addressbook setValue:@"$" forKey:[NSString stringWithFormat:@"%c", a]]; 
     NSLog(@"%@ value, %@ key", @"$",[NSString stringWithFormat:@"%c", a]); 

    } 
} 
//display the key values of addressbook 
    for(NSString *key in addressbook){ 
    NSLog(@"%@ key, %@ value", key,[addressbook objectForKey:key]); 
} 

第一的NSLog显示循环遍历一个NSMutable字典只返回最后一个项目

2012-02-27 16:02:31.886 Adresboek[4692:503] $ value, a key 
2012-02-27 16:02:31.889 Adresboek[4692:503] $ value, b key 
2012-02-27 16:02:31.890 Adresboek[4692:503] $ value, c key 
. 
. 
. 
2012-02-27 16:02:31.911 Adresboek[4692:503] $ value, x key 
2012-02-27 16:02:31.912 Adresboek[4692:503] $ value, y key 
2012-02-27 16:02:31.913 Adresboek[4692:503] $ value, z key 

第二NSLog的工作只显示最后一个元素

2012-02-27 16:02:31.914 Adresboek[4692:503] z key, $ value 

嗯,当然。每次在循环中创建一个新的NSMutableDictionary。将创建移动到循环之前。

for(char a = 'a'; a <= 'z'; a++){ 
     addressbook=[[NSMutableDictionary alloc] init]; 

addressbook=[[NSMutableDictionary alloc] init]; 
for(char a = 'a'; a <= 'z'; a++){ 
+0

谢谢我看不到明显的东西,有时如果别人看着它,它有时会有帮助。 – Stofke 2012-02-27 15:28:49