从NSMutableArray中删除for循环中的对象 [英] Deleting objects within a for loop from a NSMutableArray

查看:89
本文介绍了从NSMutableArray中删除for循环中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 UITableView 以及数组中的每个对象,它们是 UITableView ,如果他们遇到某个 if 语句,我会删除它们。我的问题是它只删除数组中的每个其他对象。

I am working with a UITableView and for each of the objects in the array that is the datasource for the UITableView, I am deleting them if they meet a certain if statement. My problem is that it only deletes every-other object from the array.

代码:

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];
    }
}

这有什么问题?

推荐答案

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

You must run your loop backwards, i.e.

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

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

If you are running it the other way round, removing an object at index position i moves the objects in the array that are behind i one position forward. In the end you will even run over the bounds of your array.

这篇关于从NSMutableArray中删除for循环中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆