开发者

iterate list and remove items from it in objective-c?

开发者 https://www.devze.com 2023-01-31 11:00 出处:网络
Objective-c 开发者_运维技巧have a built-in list iterantor via \'for(a in b) syntax that works fine with NSArray and other collections. But is it possible to remove items during such iteration without

Objective-c 开发者_运维技巧have a built-in list iterantor via 'for(a in b) syntax that works fine with NSArray and other collections. But is it possible to remove items during such iteration without ugly tricks like

for( int i = 0, i < [array count]; i ++ )
{
  if( condition )
  {
    [array removeItemAtIndex : i];
    i --;
  }
}


You can iterate array in the reverse order so you won't need to extra adjust index:

for( int i = [array count]-1; i >=0; --i)
{
   if( condition )
   {
      [array removeItemAtIndex : i];
   }
}

Or accumulate indexes to delete in indexset while enumerating and then delete all elements at once:

NSMutableIndexSet *indexes = [[NSMutableIndexSet alloc] init];
for( int i = 0, i < [array count]; i ++ )
{
  if( condition )
  {
    [indexes addIndex : i];
  }
}
[array removeObjectsAtIndexes:indexes];
[indexes release];

I would choose 2nd option because changing array while enumerating may be not a good style (although it won't give you errors in this particular case)


No, mutating a collection while enumerating it is explicitly forbidden. You could add the objects that should be removed to a second temporary mutable array and then, outside the loop, remove the objects in that array from the original with removeObjectsInArray:.


I wouldn't Call it a dirty trick to iterate backwards through the array. for(int i=array.count-1;i>=0;i--) if(condition) [array removeItemAtIndex:i];


If I need it I copy my array and enumerate one while the other is mutating

NSArray *arr = firstArr;
for( int i = [array count]-1, i >=0; --i)
{
   if( condition )
   {
      [firstArr removeItemAtIndex : i];
   }
}

but I think Vladimir's example is the better one ;) (just to have all possibilities)

0

精彩评论

暂无评论...
验证码 换一张
取 消