如何在枚举期间删除NSMutableArray或NSMutableDictionary中的元素? [英] How to remove elements in NSMutableArray or NSMutableDictionary during enumeration?

查看:83
本文介绍了如何在枚举期间删除NSMutableArray或NSMutableDictionary中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于块的枚举,类似于以下代码:

I am using block based enumeration similar to the following code:

[[[rows objectForKey:self.company.coaTypeCode] objectForKey:statementType] 
    enumerateObjectsWithOptions:NSEnumerationConcurrent 
                     usingBlock:^(id coaItem, NSUInteger idx, BOOL *stop) { 
// block code here
}]

我想在枚举过程中删除某些对象,具体取决于它们的对象值.

I would like to remove some of the objects during the enumeration process depending on the their object values.

我该怎么做?我知道在枚举期间通常无法操作可变数组或字典(NSMutableArray或NSMutableDictionary).

How could I do this? I know that manipulating an mutable array or dictionary (NSMutableArray or NSMutableDictionary) during enumeration is usually not possible.

实现此目标的最佳方法是什么?

What would be the best way to implement this?

谢谢!

推荐答案

由于枚举过程中无法从数组或字典中删除对象,因此必须累积要删除的项目,然后将其全部删除枚举之后.

Since you can't remove objects from an array or dictionary during enumeration, you'll have to accumulate the items you want to delete, and then delete them all after the enumeration.

如果要处理数组,则可以累加索引.

If you're dealing with an array, you can just accumulate the indices.:

NSMutableIndexSet *indexesToDelete = [NSMutableIndexSet indexSet];
NSUInteger currentIndex = 0;

for (id obj in yourArray) {
    //do stuff with obj
    if (shouldBeDeleted(obj)) {
        [indexesToDelete addIndex:currentIndex];
    }
    currentIndex++;
}

[yourArray removeObjectsAtIndexes:indexesToDelete];

由于未定义NSDictionary中的键顺序,因此对于NSMutableDictionary,您将不得不累积键:

Since the order of the keys in an NSDictionary is undefined, for an NSMutableDictionary you'll have to accumulate keys instead:

NSMutableArray *keysToDelete = [NSMutableArray array];

for (id obj in [yourDictionary keyEnumerator]) {
    //do stuff with obj
    if (shouldBeDeleted(obj)) {
        [keysToDelete addObject:obj];
    }
}

[yourDictionary removeObjectsForKeys:keysToDelete];

如果要用块枚举,这是同一件事.在声明该块的范围内声明该枚举数,它将被保留并正常工作.

It's the same thing if you're enumerating with a block. Declare the enumerator in the same scope where you declare the block and it will be retained and just work.

也值得研究3年前的问题:最佳方法要在迭代时从NSMutableArray中删除?.

Also worth looking at this question from 3 years ago: Best way to remove from NSMutableArray while iterating?.

这篇关于如何在枚举期间删除NSMutableArray或NSMutableDictionary中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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