在以下代码中:
//anArray is a Array of Dictionary with 5 objs.
//here we init with the first
NSMutableDictionary *anMutableDict = [[NSMutableDictionary alloc] initWithDictionary:[anArray objectAtIndex:0]];
... use of anMutableDict ...
//then want to clear the MutableDict and assign the other dicts that was in the array of dicts
for (int i=1;i<5;i++) {
[anMutableDict removeAllObjects];
[anMutableDict initWithDictionary:[anArray objectAtIndex:i]];
}
为什么这次崩溃?如何清除一个nsmutabledict并分配一个新的dict?
谢谢你的家伙。
马科斯。
答案 0 :(得分:3)
你永远不会“重新启动”物体。初始化旨在用于新alloc
ed实例,并且可能在初始化完成后进行假设。在NSMutableDictionary的情况下,您可以使用setDictionary:
用新词典或addEntriesFromDictionary:
完全替换字典的内容,以添加来自另一个字典的条目(除非有除去当前条目冲突)。
更一般地说,您可以释放该字典并在数组中生成mutableCopy
字典。
答案 1 :(得分:2)
如果您使用自动释放的字典,您的代码将更加简单:
NSMutableDictionary *anMutableDict = [NSMutableDictionary dictionaryWithDictionary:[anArray objectAtIndex:0]];
... use of anMutableDict ...
for (int i=1; i<5; i++)
{
anMutableDict = [NSMutableDictionary dictionaryWithDictionary:[anArray objectAtIndex:i]];
}
但是我没有看到你最后那个循环的重点。
答案 2 :(得分:1)
这不是你使用init / alloc的方式。相反,尝试:
//anArray is a Array of Dictionary with 5 objs.
//here we init with the first
NSMutableDictionary *anMutableDict = [[NSMutableDictionary alloc] initWithDictionary:[anArray objectAtIndex:0]];
... use of anMutableDict ...
//then want to clear the MutableDict and assign the other dicts that was in the array of dicts
for (int i=1;i<5;i++) {
[anMutableDict removeAllObjects];
[anMutableDict addEntriesFromDictionary:[anArray objectAtIndex:i]];
}