1

Possible Duplicate:
Best way to remove from NSMutableArray while iterating?

Mods: I realized this was a duplicate of this question, can you close/delete it?

Community
  • 1
  • 1
Oblivious Sage
  • 3,326
  • 6
  • 37
  • 58

2 Answers2

6

If you don't want to create a temporary or new array, you can use this:

NSMutableArray *array = ...; // your mutable array

NSIndexSet *toBeRemoved = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    // The block is called for each object in the array.
    BOOL removeIt = ...; // YES if the element should be removed and NO otherwise
    return removeIt;
}];
[array removeObjectsAtIndexes:toBeRemoved];

(But a temporary NSIndexSet is used.)

Remark: My thought was that it might be more efficient to remove all matching elements "at once" instead of removing each element separately during the iteration, as suggested by Richard J. Ross III.

But a short test showed that this is not the case. Removing every second element from an array with 1000000 elements takes almost the same time with both methods on my computer.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
2

You can use an NSPredicate to do this, see this SO question and answer.

https://stackoverflow.com/a/129942/36984

And the Apple docs for this:

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/filterUsingPredicate:

Community
  • 1
  • 1
BP.
  • 10,033
  • 4
  • 34
  • 53