删除for循环没有副作用的项目? [英] Remove items in a for loop without side effects?

查看:156
本文介绍了删除for循环没有副作用的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我可以删除一个Objective-C 循环的项目吗? >例如,这是好吗?

$ p $ for(id item in items){
if([item customCheck] ){
[items removeObject:item]; //这里好吗?


解决方案

如果您在循环的快速枚举中更改数组,则会出现错误。创建一个数组的副本,迭代它,并从您的原始。

  NSArray * itemsCopy = [items copy]; 
$ b $(itemCopy中的id项){
if([item customCheck])
[items removeObject:item]; //这里没关系
}

[itemsCopy release];


Can I remove items that I am looping through in an Objective-C for loop without side effects?

For example, is this ok?

for (id item in items) {
   if ( [item customCheck] ) {
      [items removeObject:item];   // Is this ok here?
}

解决方案

No, you'll get an error if you mutate the array while in a fast enumeration for loop. Make a copy of the array, iterate over it, and remove from your original.

NSArray *itemsCopy = [items copy];

for (id item in itemsCopy) {
   if ( [item customCheck] )
      [items removeObject:item];   // Is this ok here
}

[itemsCopy release];

这篇关于删除for循环没有副作用的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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