我想添加一个不同的Dictionary作为另一个键字典的值,但是在我的循环中,我发现我的所有字典键都添加了相同的值。 这是我的代码:
for (MyObject *message in messages) {
int value = [key intValue] +1;
[mess setObject:message.body forKey:@"msg"];
[mess setObject:message.bareJidStr forKey:@"sender"];
[mess setObject:[element attributeStringValueForName:@"to"] forKey:@"reciever"];
[mess setObject:message.timestamp forKey:@"date"];
[[self messagesHistory] setObject:mess forKey:[NSString stringWithFormat:@"%d",value]];
}
有些东西不能正常工作,但我可以找出原因! 谢谢你的帮助。
答案 0 :(得分:2)
因为您要添加相同的字典
你必须在循环之前有这一行
NSMutableDictionary *mess = [NSMutableDictionary dictionary];
因此您只创建一个字典并将其用作所有键的值
你需要在循环中移动这一行
for (MyObject *message in messages) {
// create a new dictionary for each value
NSMutableDictionary *mess = [NSMutableDictionary dictionary];
int value = [key intValue] +1;
[mess setObject:message.body forKey:@"msg"];
[mess setObject:message.bareJidStr forKey:@"sender"];
[mess setObject:[element attributeStringValueForName:@"to"] forKey:@"reciever"];
[mess setObject:message.timestamp forKey:@"date"];
[[self messagesHistory] setObject:mess forKey:[NSString stringWithFormat:@"%d",value]];
}
答案 1 :(得分:1)
在循环中创建一个“mess”对象,否则所有值都使用相同的“mess”对象。
for (MyObject *message in messages)
{
int value = [key intValue] +1;
mess = [NSMutableDictionary new];
[mess setObject:message.body forKey:@"msg"];
[mess setObject:message.bareJidStr forKey:@"sender"];
[mess setObject:[element attributeStringValueForName:@"to"] forKey:@"reciever"];
[mess setObject:message.timestamp forKey:@"date"];
[[self messagesHistory] setObject:mess forKey:[NSString stringWithFormat:@"%d",value]];
}