2011-04-01 124 views
1

我有一個for循環,由於某種原因不會允許我刪除數組中的所有對象,只有少數幾個。缺陷循環!

我在做什麼錯?

- (void)deleteAllObjects { 
    AppDelegate *appDel = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
    NSLog(@"Before: %d", [histArray count]); 
    for (int i = 0; i < [histArray count]; i++) { 
     History *h = (History *)[histArray objectAtIndex:i]; 
     [[appDel managedObjectContext] deleteObject:h]; 
     [histArray removeObject:h]; 
     [appDel saveContext]; 
     NSLog(@"During: %d", [histArray count]); 
     [self fetchUpdates]; 
    } 
    NSLog(@"After: %d", [histArray count]); 
} 

回答

4

您正在通過調用[histArray removeObject:h]來縮短數組。既然你正在刪除histArray中的每一個對象,爲什麼不等到循環完成之後再用[histArray removeAllObjects]一次刪除所有對象呢?

另一種解決方案是循環遍歷數組,從結尾到開頭。

2

在迭代其內容時不要修改數組。如果您使用快速迭代,這一點尤其重要,但即使您沒有,也可能會出現問題,因爲它在這裏。問題在於你通過移除對象來改變對象的位置。

如果你必須這樣做,你可以:

  • 取下陣列年底開始,向開始工作,或
  • 不要增加索引的對象。如果您在[array count]次數組的開始處刪除對象,則將刪除所有對象。

但是,如果您使用快速迭代或者如果您使用的是枚舉器,請不要更改數組。

0

嘗試改變:

for (int i = 0; i < [histArray count]; i++) { 

到:

for (int i = [histArray count] - 1; i >= 0; i--) { 

你的電流回路不工作的原因是,當你刪除索引0,索引1至50不住宿他們在哪裏,他們洗牌,以便1變成0,2變成1等等。

因此,當您刪除索引1時,通過循環的下一次,您將在索引0處將新項目留在那裏。

通過向後循環,您可以刪除此混洗,並刪除所有索引。

1

您正在從「histArray」中刪除,並且您正在同一陣列上運行您的循環。我認爲需要在每次迭代後重置索引。 刪除語句「[histArray removeObject:h];」從你的循環和循環結尾調用你的數組中的removeAll函數來清除它。這將解決這個問題,

下面是修改後的代碼,

- (void)deleteAllObjects { 
    AppDelegate *appDel = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
    NSLog(@"Before: %d", [histArray count]); 
    for (int i = 0; i < [histArray count]; i++) { 
     History *h = (History *)[histArray objectAtIndex:i]; 
     [[appDel managedObjectContext] deleteObject:h]; 
     [appDel saveContext]; 
     NSLog(@"During: %d", [histArray count]); 
     [self fetchUpdates]; 
    } 
    [histArray removeAllObjects]; 
    NSLog(@"After: %d", [histArray count]); 
}