2016-02-12 81 views
3

所以我想從我的數組中選擇對象,以便能夠在我進行IBAction時刪除它們。我想:從NSArray中選擇對象進一步用IBAction刪除

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { 
if (self.editEnabled) { 


    RDNote *selectedNote = [self.notes objectAtIndex:indexPath.row]; 
    if (selectedNote.isSelected) { 
     selectedNote.selected = NO; 
     for (NSIndexPath *indexPathFromArray in self.indexPathsOfSelectedCells) { 
      if (indexPathFromArray.row == indexPath.row) { 
       [self.mutableCopy removeObject:indexPathFromArray]; 
      } 
     } 
    } else { 
     selectedNote.selected = YES; 
     [self.indexPathsOfSelectedCells addObject:indexPath]; 
    } 
    [self.collectionView reloadData]; 

IBAction爲:

- (IBAction)didTapTrashBarButton:(id)sender { 
NSMutableArray *mutableNotes = [NSMutableArray arrayWithArray:self.notes]; 
for (NSIndexPath *indexPath in self.indexPathsOfSelectedCells) { 
    [mutableNotes removeObjectAtIndex:indexPath.row]; 
} 
self.notes = [NSArray arrayWithArray:mutableNotes]; 

[self.collectionView performBatchUpdates:^{ 
    [self.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithArray:self.indexPathsOfSelectedCells]]; 

} completion:^(BOOL finished) { 
    self.indexPathsOfSelectedCells = nil; 
    [self activateEditMode:NO]; 
    [self saveDataToFile:self.notes]; 
}]; 

}

但我有索引的問題,例如:(有時顯示我

,如果該項目被選中檢查對象索引2不在[0..1]之間的錯誤),並且在選擇多個對象並刪除它們時存在錯誤。 請幫我提供一些我可以使用的其他方法的建議,一個代碼將是完美的!謝謝!

+0

什麼是'IBAction'中的'indexPath.row'?您在IBActions中傳遞UI對象,而不是索引路徑。 – trojanfoe

+0

使用CoreData而不是mutableCopy。 –

+0

我是新來的客觀請給我一個例子的鏈接,謝謝! –

回答

3

此問題棱因爲: 讓說你有陣1,2,3,4,5

五個對象,你正在運行一個循環去除對象的基礎上被選擇行indexpath。現在你的索引路徑包含第一行和第三行。

第一次執行它時,您將刪除對象1.現在2,3,4,5將保留在數組中。現在第二次你的indexpath.row是第三。它將刪除第三個對象,它是4,但在實際數組中它是3.

您的代碼有時會崩潰,因爲如果您選擇了第一行和最後一行。在這種情況下,我選擇了1和5.現在我的indexpaths數組會說我必須檢查objectsAtIndexes 1和5.

執行循環時,我將刪除索引1處的對象。現在我將剩下2, 3,4,5。在第二次迭代時,它會說刪除objectAtIndex 5,因爲索引5不存在,因爲現在我們有4個元素在數組中。

在這種情況下,這樣做的最好方法是嘗試從末端移除數組中的元素,如先移除第5個元素,然後移至其他位置。以相反的順序運行你的循環。

NSInteger i = [self.indexPathsOfSelectedCells count]-1; 

while (i > 0){ 
    NSIndexPath *indexPath = [self.indexPathsOfSelectedCells objectAtIndex:i]; 
    [mutableNotes removeObjectAtIndex:indexPath.row]; 
    i--; 
}