循环遍历NSMutableDictionary仅返回最后一项

时间:2012-02-27 15:06:00

标签: objective-c

//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显示工作循环

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

1 个答案:

答案 0 :(得分:1)

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

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

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