2011-05-17 18 views
0

我正在爲我的應用發送一個更新,這將需要更新用戶數據庫。我將數據存儲在屬性列表中。基本上,陣列中的每個點都NSMutableDictionaries,我需要添加鍵,更換鍵等在枚舉時替換數組中的對象?

我嘗試以下,但它產生的NSException,

for (NSMutableDictionary *dict in myArray) { 

    if ([dict objectForKey:@"someKey"] == nil) { 

     //Extract the value of the old key and remove the old key 
     int oldValue = [[dict objectForKey:@"key1"] intValue]; 
     [dict removeObjectForKey:@"key1"]; 

     [dict setValue:[NSString stringWithFormat:@"%d pts", oldValue] forKey:@"newKey"]; 

     //Add new keys to dictionnary 
     [dict setValue:@"some value" forKey:@"key2"]; 
     [dict setValue:@"some value" forKey:@"key3"]; 
     [dict setValue:@"some value" forKey:@"key4"]; 

     [self.myArray replaceObjectAtIndex:index withObject:dict]; 

    } 

我應該怎麼做來更新我的數據以上述方式?

回答

1

問題是你不能用快速枚舉修改你正在迭代的數組。

代碼片段根本不需要replaceObjectAtIndex:withObject:調用,因爲您用同一個對象替換對象!所以,如果你刪除該行,一切都應該工作。

一般情況下,你能避免類似的問題,如果你使用普通的舊與索引循環,即

for (int i = 0; i < [array count]; i++) { 
    id obj = [array objectAtIndex:i]; 
    // ... 
} 

,因爲這不會弄亂快速枚舉。

+0

真棒!非常感謝,我不能相信這是多麼簡單 – cgossain 2011-05-17 20:54:24

0

首先,確保myArray是一個NSMutableArray。如果是這樣,如果你調試了類似_NSArrayI unrecognized selector sent to instance的代碼,你可能會看到一些錯誤。_NSArrayI意味着它是一個不可變的數組。這很煩人,但試着做這個測試。然後你可以用mutableArray替換你的myArray。

NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:self.myArray]; 
for (NSMutableDictionary *dict in mutableArray) { 

if ([dict objectForKey:@"someKey"] == nil) { 

    //Extract the value of the old key and remove the old key 
    int oldValue = [[dict objectForKey:@"key1"] intValue]; 
    [dict removeObjectForKey:@"key1"]; 

    [dict setValue:[NSString stringWithFormat:@"%d pts", oldValue] forKey:@"newKey"]; 

    //Add new keys to dictionnary 
    [dict setValue:@"some value" forKey:@"key2"]; 
    [dict setValue:@"some value" forKey:@"key3"]; 
    [dict setValue:@"some value" forKey:@"key4"]; 

    [mutableArray replaceObjectAtIndex:index withObject:dict]; 

} 
} 
+0

根本不能解決問題。你真的應該知道你的工作對象是否可變。這不是一個煩惱,這是一個非常明確和有意義的區別。 – Eiko 2011-05-17 20:42:21

+0

我完全明白應該聲明NSMutableArray,但是我懷疑他創建了@屬性(非原子,副本)NSMutableArray * myArray'。 'copy'實際上會創建一個不可變的數組而不是NSMutableArray,你可以看到你是否運行代碼。你會看到底層的具體類實現是'_NSArrayI' – 2011-05-17 20:55:35

+0

在這種情況下,正確的修復將是正確實現setter方法。只是在這裏製作一個可變副本並不能解決問題本身。它寧願掩蓋錯誤。 – Eiko 2011-05-17 21:05:03

1

創建數組的副本並枚舉副本。通過這種方式,你可以安全地修改原來的一個:

for (id obj in [NSArray arrayWithArray:entries]) { 
    [entries removeObject:obj]; 
} 

不要使用:

for (int i = 0; i < [array count]; i++) { 
    id obj = [array objectAtIndex:i]; 
    [array removeObject:obj]; 
} 

這樣做是因爲,在取出後,在數組索引將被抵消!

+1

難道你不能只是拋出一個'if'語句,並在其中刪除對象和'我 - ;'? – 2012-05-14 22:33:00