Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Collection was modified..." Issue

I've got a function that checks a list of objects to see if they've been clicked and fires the OnClick events accordingly. I believe the function is working correctly, however I'm having an issue:

When I hook onto one of the OnClick events and remove and insert the element into a different position in the list (typical functionality for this program), I get the "Collection was modified..." error.

I believe I understand what is going on:

  • The function cycles through each object firing OnClick events where necessary
  • An event is fired and the object changes places in the list per the hooked function
  • An exception is thrown for modifying the collection while iterating through it

My question is, how to do I allow the function to iterate through all the objects, fire the necessary events at the proper time and still give the user the option of manipulating the object's position in the list?

like image 576
Tyler Murry Avatar asked Jul 30 '26 06:07

Tyler Murry


1 Answers

There are two general solutions to this kind of problem:

  • Make a copy of the list. Iterate over the copy.
  • Make a list of the changes that need to happen. Apply the changes after you've finished iterating.

The "use indices" option doesn't sound like it's suitable if you want to decouple the code that makes the changes from the code that does the looping.

like image 165
tc. Avatar answered Aug 01 '26 20:08

tc.