Oliver
Oliver

Reputation: 23510

iPhone - Changing an array while it's enumerated

I have a mutable array that contains the sounds that are being played.

I have a continous process that parse that array to adjust volumes and some other things.

Sometimes, a new sound is played and must be added to that array just before it's play starts.
And sometimes, I have a crash because my array "was mutated while being enumerated".

How may I solve that ?

Upvotes: 0

Views: 69

Answers (2)

Philipp Schlösser
Philipp Schlösser

Reputation: 5219

It would be nice to see any code here. But according what you are saying, i think the problem lies in the way that you use to iterate through the array. I guess it looks like this:

for ( type *object in myArray) {
    ...
}

Now, as you exception tells you, you can't modify the array while doing this. If you, on the other hand, access the array's values via the indexes, it should work:

for (int i = 0; i < myArray.count; i++) {
    [myArray objectAtIndex:i]...
}   

Keep in mind however, that the indexes aren't 'stable' that way, especially if you remove objects.

Upvotes: 1

nevan king
nevan king

Reputation: 113747

You can't easily change an array while it's enumerating.

Enumerate through the array and note the new sound to be added (using a variable, or a separate array if you need to note more than one). When the enumeration is finished, add the sound to the array.

Alternatively, make a copy of the array, enumerate the copy and add the sound to the original one when you need to.

Upvotes: 1

Related Questions