Reputation: 703
I am facing an issue in which NSManagedObject is not showing issues on MainThread but on accessing same NSManagedObject in background thread, it is showing error: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
I actually not having any idea that why it is happening.
I am fetching this NSManagedObject by mainContext using peform{} block method. So this returned object works fine on main thread but on accessing this object in background thread, i am getting crash.
I don't know clearly that what extra information should I provided to describe my problem.
If anyone have any idea about my problem, then let me know about this.
Upvotes: 0
Views: 493
Reputation: 6635
Managed objects (and contexts) can only be accessed from specific threads. If you want to access a managed object from a background thread you need to create a context with private queue concurrency, and then use the performBlock:
method.
let bgContext = NSManagedObjectContext(concurrencyType: privateQueueConcurrencyType)
bgContext.perform {
// code which accesses managed object
}
If you need to take a specific entity from the main thread and access it in the background, you can take the object's managedObjectID
from the main thread and then call existingObject(with:)
in the background block to get the same entity in the background context.
Upvotes: 2