My question is similar to this one.
Background
I'm creating a large number of objects in a core data store using NSOperations to speed things up.
I've followed all the Core Data multithreading rules - I've got a single persistent store coordinator and a managed object context per thread that on save is merging back to the main managed object context.
The Problem
When the number of threads running at once is more than 1, I get the exception logged on save of my core data store:
NSExceptionHandler has recorded the following exception:
NSInternalInconsist开发者_开发知识库encyException -- optimistic locking failure
What I've Tried
My code that creates new entities is quite complex - it makes entities that have relationships with other entities that could be being created in a separate thread.
If I replace my object creation routine with some very simple code just making non-related entries, everything works perfectly.
Initially, as well as the exceptions, I was getting a save error saying core data couldn't save due to the merge failing.
I read the docs and realised I needed a merge policy on the Managed Object Context I was saving to. I set this up and as this question states, the save error goes away, but the exception remains.
My Question
Do I need to worry about these exceptions? If I do need to get rid of the exceptions, any ideas on how I do it?
You need to catch that exception and then print out all of the information associated with it to determine the exact cause. Exceptions are quite rare in Core Data and definitely should NEVER be ignored.
However you have not given us enough information to help you track it down so the first step is to unroll that exception and see what is going on.
Exceptions in Cocoa are a sign that something really nasty has happened and it's best to quit ASAP. In general Cocoa uses return values and input parameters for communicating error conditions.
Are you creating a new NSManagedObjectContext
for the new thread? The Apple doc Multi-Threading with Core Data gives guidelines for multithreading with Core Data. It recommends:
Create a separate managed object context for each thread and share a single persistent store coordinator.
精彩评论