Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData change relationships in a loop

I have a simple model like this:

item  category --> category 
      <--- items

and following data:

item A -> category blue
item B -> category blue
item C -> category blue
item D -> category green
item E -> category green

What I want to achieve is to change all items where the category is green to blue.

Following code produced only an error:

Two categories already exist:

blueCategory
greenCategory


for (Item *aItem in [greenCategory.items]) {
    [aItem setCategory:blueCategory];
}

Error:

'NSGenericException', reason: '* Collection <_NSFaultingMutableSet: 0x8a0ef70> was mutated while being enumerated.'

My Question is: How could I alter the category in items within a loop?

like image 638
madcat Avatar asked Jan 26 '26 14:01

madcat


1 Answers

The problem is that you can't change (mutate) a collection like your greenCategory.items set while you're looping over it, which is what you're doing when you change the category of the items in that set. What you have to do is create a separate collection and loop over it instead.

NSArray *greenCategoryItemsArray = [greenCategory.items allObjects];

for (Item *aItem in greenCategoryItemsArray) {
    [aItem setCategory:blueCategory];
}
like image 78
Adam Maras Avatar answered Jan 28 '26 04:01

Adam Maras



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!