以forin的方式遍历数组时进行删除操作的注意点

时间:2022-08-25 15:17:50

今天在修改某项需求的时候,需要在遍历的时候将匹配项移除掉,采用的时forin的方式遍历,然后运行的时候却crash掉了

for (NSString*str in self.btnArray) {
if ([imageName isEqualToString:str]) {
[self.btnArray removeObject:str];
}
}

于是我换了常规的方法来遍历数组,同样的也是在匹配的时候将匹配项移除掉,然后运行,没有crash,能完美处理

for(int i = 0; i < self.btnArray.count; i++) {
if ([imageName isEqualToString:self.btnArray[i]]) {
[self.btnArray removeObject:self.btnArray[i]];
       i--; }
}

 

 然后我就想,到底什么原因呢?于是我在apple官方文档查了下快速遍历的利弊,发现这么一段话:

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSEnumerator_Class/index.html

You send nextObject repeatedly to a newly created NSEnumerator object to have it return the next object in the original collection. When the collection is exhausted, nil is returned. You cannot “reset” an enumerator after it has exhausted its collection. To enumerate a collection again, you need a new enumerator.

The enumerator subclasses used by NSArrayNSDictionary, and NSSet retain the collection during enumeration. When the enumeration is exhausted, the collection is released.

NOTE

It is not safe to modify a mutable collection while enumerating through it. Some enumerators may currently allow enumeration of a collection that is modified, but this behavior is not guaranteed to be supported in the future.

 大概的意思是说,快速遍历的原理是根据enumerator对象内部的计数器,调用nextObject方法来实现返回下一个数组元素的,直到元素全部返回就会返回nil,于是整个enumerator对象就遍历完了;同时也提醒,以这种原理来遍历enumerator对象的话,无论对这个对象做什么操作,对象的计数器都不会被重置!

注意下面的NOTE,建议最好不要再快速遍历的时候修改enumerator,否则不保证是安全的.

 

由此就明白了,可能是我们在快速遍历的时候,移除掉一个元素,但是计数器依旧是原来的,那么在遍历到最后会继续调用nextObject方法,而此时实际上已经全部遍历完了,但是系统并不知道,还在遍历,也就是越界;当发现没有元素时,就crash了;而我写的常规遍历法为什么就可以呢,那是因为i < self.btnArray.count,这个判断条件中,当数组元素个数变化时,self.btnArray.count也在变,就不会出现数组越界的情况,因此第二种方法是可行的;

 

但是我还是想用第一种快速遍历的方法,因为我不需要按照顺序遍历,而且我希望能以最快的速度遍历,那么有没有办法解决呢?最后我想当一个办法,既然在遍历的时候移除元素后,计数器没有变,为了防止数组越界,那么我是否可以直接终止掉遍历呢?这样不就不会crash了吗?

for (NSString*str in self.btnArray) {
if ([imageName isEqualToString:str]) {
[self.btnArray removeObject:str];
break;
}
}

 我在移除元素后,加一个break,结束当前的遍历,运行后,无问题!

 

另外我在网上看到有网友说可以逆序遍历,再删除,同样不会crash,参考地址:

http://m.blog.csdn.net/blog/Zhangzhan_zg/38453305

 我提出的这个方案,只能删除数组中的一个元素,如果要删除多个的话,可以参考:
Zhangzhan_zg的博客:遍历可变数组的同时删除数组元素的几种解决方案