2010-03-17 36 views
1

在下面的代碼:的NSMutableDictionary,分配,init和reiniting

//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]]; 
} 

爲什麼這會崩潰嗎?如何正確的方式來清除無效的字典並分配新的字典?

謝謝你的。

馬科斯。

回答

3

您不會「重新啓動」對象 - 永遠。初始化意味着在新編寫的實例上使用,並且可能會在初始化完成後做出假設,但這種假設不正確。在NSMutableDictionary的情況下,您可以使用setDictionary:將字典的內容用新字典或addEntriesFromDictionary:完全替換爲從其他字典添加條目(除非存在衝突時不刪除當前條目)。

更一般地說,您可以釋放該字典並在數組中創建字典的mutableCopy

+0

好的!這是一個很好的解釋! – 2010-03-17 03:47:43

+0

@Marcos:那麼你應該*接受* @查克的回答。這是履行你的問題的好方法。 – 2010-03-17 14:07:24

2

如果使用自動釋放的字典,你的代碼就會簡單得多:

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

... use of anMutableDict ... 

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

但我沒有看到環你在年底有點。

+0

ow,對不起,這是一個不完整的代碼。在循環中我加載字典然後使用它。 – 2010-03-17 03:21:48

+0

@Marcos,那麼我上面的例子應該爲你工作。 – 2010-03-17 03:23:03

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]]; 
} 
相關問題