从NSMutableArray中删除for循环中的对象

时间:2013-01-23 02:38:06

标签: ios objective-c xcode uitableview nsmutablearray

我正在使用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];
    }
}

这有什么问题?

2 个答案:

答案 0 :(得分:6)

你必须向后运行你的循环,即

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

如果您反过来运行它,则删除索引位置i处的对象会将数组中的对象向前移动i一个位置。最后,您甚至可以遍历数组的边界。

答案 1 :(得分:1)

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

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

时,

减少removeObjectAtIndex

    if (cell.imageView.image == isCkDone) {
        ...
        --i ;
        ...
    }
当您的条件不符合时,

或仅增加i

for ( int i=0 ; i<c ; ) {
    ...
    if (cell.imageView.image == isCkDone) {
        ...
    } else {
    ++i ;
    }
相关问题