One more "Mutated while being enumerated" issue

776 views Asked by At

I faced "Collection <_NSFaultingMutableSet: 0x7fac9c011190> was mutated while being enumerated" issue.

I know what it means, I found it on SO. I spotted the line which causes this exception. But I still can't get what exactly I'm mutating here. Could you please help me figure that out?

- (void)addEntitiesObject:(Entity *)value {
    for (Group* group in value.groups) {
        Group* groupToAddObjectTo = nil;
        for (Group* tabGroup in self.tab.groups) {
            if (group.title == tabGroup.title) {
                groupToAddObjectTo = tabGroup;
            }
        }
        if (!groupToAddObjectTo)
            groupToAddObjectTo = [self.fetchController createGroup];

        groupToAddObjectTo.title = group.title;
        [groupToAddObjectTo addEntitiesObject:value]; //THIS LINE IS A TROUBLE
        [self.tab addGroupsObject:groupToAddObjectTo];
    }
}

The method addEntitiesObject that causes a problem is generated by XCode with "Create NSManagedObject subclass...". I never define it.

Method "createGroup" only inserts new Group in CoreData with

    Group* group = (Group*)[NSEntityDescription insertNewObjectForEntityForName:@"Group" inManagedObjectContext:self.managedObjectContext];

and returns the group.

So my point is that I'm not using groupToAddObjectTo while it is in the loop where it is assigned to an element of NSSet, so what's the problem here?

1

There are 1 answers

2
Paulw11 On BEST ANSWER

If you have an inverse relationship from groups back to the value entity, then adding the entity to a group will modify the value.groups property - which will cause your error as your outer loop is enumerating value.groups.

Either remove the inverse relationship, or if you need to keep it, copy the value.groups property and enumerate the copy.