Having spent a few hours on this issue, I can only find solutions to this when I am using core data on background threads, not on the main thread.
In my setup I have one operation occurring in the background via a custom NSOperation class that is downloading data and saving to core data. While that is happening in the background, on the main thread I do more core data operations that cause the "Collection was mutated while being enumerated" error.
Here is the code for the NSOperation class:
- (id)initWithContext:(NSManagedObjectContext*)parentContext andTrip:(MPTrip *)trip
{
self = [super init];
if(self) {
self.trip = trip;
self.parentContext = parentContext;
}
return self;
}
- (void)main
{
self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
self.context.persistentStoreCoordinator = [self.parentContext persistentStoreCoordinator];
[self.context performBlockAndWait:^
{
[self asyncDownloadAll];
}];
}
And here is how it is initialized and started from the main thread:
trip.downloader = [[MPAsyncDownloader alloc] initWithContext:trip.managedObjectContext andTrip:trip];
[self.operationQueue addOperation:self.trip.downloader];
Now I believe I am doing everything correct in making a new MOC based off the parent one, and multiple background threads can run at the same time without causing any issue, its just when I try to do a core data operation on the main thread via
result = [context executeFetchRequest:request error:&error];
That the crash happens. Any help is appreciated thanks!