1

在以下代码中:

//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 并分配新字典的正确方法是什么?

多谢你们。

马科斯。

4

3 回答 3

3

你永远不会“重新初始化”对象。初始化旨在用于新alloc编辑的实例,并且可能会在初始化完成后做出不正确的假设。在 NSMutableDictionary 的情况下,您可以使用setDictionary:新字典完全替换字典的内容或addEntriesFromDictionary:添加另一个字典中的条目(除非存在冲突,否则不会删除当前条目)。

更一般地说,您可以只释放该字典并mutableCopy在数组中创建一个字典。

于 2010-03-17T03:29:16.410 回答
2

如果你使用自动发布的字典,你的代码会简单很多:

NSMutableDictionary *anMutableDict = [NSMutableDictionary dictionaryWithDictionary:[anArray objectAtIndex:0]];

... use of anMutableDict ...

for (int i=1; i<5; i++)
{
    anMutableDict = [NSMutableDictionary dictionaryWithDictionary:[anArray objectAtIndex:i]];
} 

但我没有看到你最后的那个循环的意义。

于 2010-03-17T03:13:57.173 回答
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]];
} 
于 2010-03-17T03:24:43.543 回答