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?
}
The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove . Therefore, the for-each loop is not usable for filtering.
The right way to remove objects from ArrayList while iterating over it is by using the Iterator's remove() method. When you use iterator's remove() method, ConcurrentModfiicationException is not thrown.
If you want to delete elements from a list while iterating, use a while-loop so you can alter the current index and end index after each deletion.
The methods are remove(), pop() and clear(). It helps to remove the very first given element matching from the list. The pop() method removes an element from the list based on the index given. The clear() method will remove all the elements present in the list.
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];
Nope:
Enumeration is “safe”—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration, an exception is raised.
Options for changing an array that you want to enumerate through are given in Using Enumerators: either copy the array and enumerate through, or build up an index set that you use after the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With