2013-01-17 42 views
-1

我有一個數組,當我遍歷數組時,我想要替換項目。如果我這樣做,這是不可能的,並會引起瘋狂?這裏是代碼:同時迭代和替換項目

for (int i = 0; i < [highlightItemsArray count]; i++){ 
    //replace the from array with the new one 
    NSMutableDictionary *tempDictionary = [NSMutableDictionary dictionaryWithDictionary:highlightItem]; 
    [tempDictionary setObject:[newHighlightItem objectForKey:@"from"] forKey:@"from"]; 
    [highlightItemsArray replaceObjectAtIndex:i withObject:tempDictionary]; 
    [indexes addIndex:i]; 
} 

只是想知道這是否在Objective-C中是合法的嗎?如果不是,那麼這樣做有什麼選擇?

+0

也不會造成任何崩潰 –

+2

這隻會失敗,如果你正在使用'快速枚舉'('對於數組{}'中的id對象)。可能有一個簡單的方法來完成你正在做的事情,但我不確定你想要達到什麼目的 – MaxGabriel

回答

0

你上面的代碼看起來不錯。

如果它崩潰它不是由於改變你的數組。

然而,在舊式的循環(同時,爲(;;),dowhile),你可以改變這些 1.初始化劑(但是這僅僅是一次執行) 2.計數器 3.條件。

但在快速枚舉的情況下,你不能做所有這些。

因此,如果您將上面的代碼與for(... in ...)結合,它會拋出一個錯誤,說試圖改變一個不可變的對象。即使你定義了你的計數器和/或數組,不變的快速枚舉將它們視爲不可變的。

0

快速和骯髒的方式來解決,這將是一個數組複製,即

NSMutableArray *higlightItemsCopy = [highlightItemsArray mutableCopy]; 
for (int i = 0; i < [highlightItemsArray count]; i++){ 
    //replace the from array with the new one 
    NSMutableDictionary *tempDictionary = [NSMutableDictionary dictionaryWithDictionary:highlightItem]; 
    [tempDictionary setObject:[newHighlightItem objectForKey:@"from"] forKey:@"from"]; 
    higlightItemsCopy[i] = tempDictionary; 
    [indexes addIndex:i]; 
} 
highlightItemsArray = higlightItemsCopy; 

沒有測試過,但類似的東西