从 NSArray 中选择对象,以便使用 IBAction 进一步删除



所以我正在尝试从我的数组中选择对象,以便在我执行 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] 之间的错误(,并且在选择多个对象并删除它们时存在错误。请帮助我提供一些我可以使用的其他方法的建议,代码将是完美的!谢谢!

出现

此问题是因为:假设数组 1,2,3,4,5 中有五个对象

您正在运行一个循环,用于根据所选行的索引路径删除对象。现在,索引路径包含第一行和第三行。

首次执行时,您将删除对象 1。现在数组中将剩下 2,3,4,5。现在第二次你的indexpath.row是第3次。它将删除第三个对象,即 4,但在实际数组中它是 3。

您的代码有时会崩溃,因为如果您选择了第一行和最后一行。在这种情况下,我选择了 1 和 5。现在我的索引路径数组会说我必须选择对象索引 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--;
}

相关内容

最新更新