1

我正在处理UITableView数组中作为 的数据源的每个对象,如果它们满足某个语句UITableView,我将删除它们。if我的问题是它只会从数组中删除所有其他对象。

代码:

UIImage *isCkDone = [UIImage imageNamed:@"UITableViewCellCheckmarkDone"];
int c = (tasks.count);
for (int i=0;i<c;++i) {
    NSIndexPath *tmpPath = [NSIndexPath indexPathForItem:i inSection:0];
    UITableViewCell * cell = [taskManager cellForRowAtIndexPath:tmpPath];
    if (cell.imageView.image == isCkDone) {
        [tasks removeObjectAtIndex:i];
        [taskManager deleteRowsAtIndexPaths:@[tmpPath]
                withRowAnimation:UITableViewRowAnimationLeft];
    }
}

这有什么问题?

4

2 回答 2

6

您必须向后运行循环,即

for (int i=c-1;i>=0;--i)

如果您以相反的方式运行它,则删除索引位置i的对象会使数组中位于i一个位置后面的对象向前移动。最后,您甚至会超出数组的范围。

于 2013-01-23T02:43:22.797 回答
1

如果您想保持循环向前运行,您可以:

i您的条件得到满足并且您removeObjectAtIndex

    if (cell.imageView.image == isCkDone) {
        ...
        --i ;
        ...
    }

i 在您的条件不满足时才增加:

for ( int i=0 ; i<c ; ) {
    ...
    if (cell.imageView.image == isCkDone) {
        ...
    } else {
    ++i ;
    }
于 2013-01-23T02:49:50.513 回答