0

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!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Check this answer out: http://stackoverflow.com/questions/3446983/collection-was-mutated-while-being-enumerated-on-executefetchrequest?rq=1 Probably this is what is happening with you. – scollaco Jul 24 '14 at 19:45
  • I don't think that is my issue since I create my background MOC context in the main of my NSOperation class, which does not run on the main thread. – user3874358 Jul 25 '14 at 14:50

0 Answers0