Core Data executeFetchRequest throws NSGenericException (Collection was mutated while being enumerated)

后端 未结 4 1536
忘掉有多难
忘掉有多难 2021-02-09 13:04

I\'m developing a iPhone app with Core Data. All user data should be synchronized with our servers. For this purpose I created a subclass of NSOperation witch loads new data fro

相关标签:
4条回答
  • 2021-02-09 13:14

    Off the top of my head: Is the "synchronization" thread adding new objects to the Department collection while iterating on it on the main thread?

    Usually, this type of exception occurs when you're modifying a collection at the same time you're enumerating it. In a multi-threaded scenario, it might also mean your collection is enumerated and updated concurrently without proper thread synchronization.

    0 讨论(0)
  • 2021-02-09 13:14

    I had same problem. You can use lock, unlock receiver. I solved this problem until now.

    0 讨论(0)
  • 2021-02-09 13:23

    The error "someCollection was mutated while being enumerated" is caused by altering a mutable collection i.e. array, dictionary, set etc, while an enumerator is stepping through it. Since you can't enumerate a moving target, this triggers an error.

    In this case, the error is most likely caused by trying to enumerate a Department's employees relationship on the main thread e.g. for display in a tableview, while the the background thread is simultaneously adding employees to the relationship.

    Did work around this, you have to freeze the UI while you merge the changes from the background thread. For tableviews, a fetched results controller (NSFetchedResultsController) with properly implemented delegate methods in the tableview controller will handle the problem nicely.

    The important thing is to send beginUpdates to the tableview before you merge the new data. This will tell the table that it's underlying data structure is being mutated so it won't try to redraw itself. When the merge is complete, send endUpdates to the tableview to cause it to display the new information.

    0 讨论(0)
  • 2021-02-09 13:26

    I had the same problem... It was solved because I was using the managedObjectContext that was created on the main thread on a background thread. The solution was to create a different ManagedObjectContext on the background thread, and use the regular persistentStoreCoordinator... it worked fine after that!

    0 讨论(0)
提交回复
热议问题