Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely loop over a mutable array while modifying it?

I have a controller which has an array holding actors. An actor is a object which will be called by the controller.

The problem: The controller iterates over the actors array and sends each actor an -actionMessage. The actor can create and register another actor with the controller, or remove an actor or even itself from the controller's actors array. It is routed through two methods:

-registerActor:(Actor*)actor;
-unregisterActor:(Actor*)actor;

So while the controller iterates over the actors array, the list of actors can change. Edit: And any newly added actor MUST go through the loop as well.

What is best practice to deal with this problem? Should I create a copy of the actors array before iterating over it?

like image 485
Proud Member Avatar asked Jul 29 '26 23:07

Proud Member


2 Answers

Create a copy of your mutable array and iterate over that.

NSArray *loopArray = [NSArray arrayWithArray: yourActorArray];

Or

NSArray *loopArray = [yourActorArray copy];
//in this case remember to release in nonARC environment
like image 108
Mario Avatar answered Aug 01 '26 11:08

Mario


This is what I usually do...

NSMutableArray *discardedItems = [NSMutableArray array];
SomeObjectClass *item;

for (item in originalArrayOfItems) {
    if ([item shouldBeDiscarded])
        [discardedItems addObject:item];
}

[originalArrayOfItems removeObjectsInArray:discardedItems];

hoping this helps.

like image 42
Ankit Srivastava Avatar answered Aug 01 '26 12:08

Ankit Srivastava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!