Reputation: 842
Can I set the relationship between objects in DIFFERENT perform blocks of the SAME NSManagedContext?
I created a private context and used (just example):
let pContext = persistentContainer.newBackgroundContext()
pContext.perform {
let user = pContext.fetch(<fetch Request>).first
pContext.performAndWait {
let book = pContext.fetch(<another fetch request>).first
book.name = "skjkjd"
pContext.save()
book.author = user
pContext.save()
}
}
May this code produce following error and in which cases?
Fatal Exception: NSInvalidArgumentException Illegal attempt to establish a relationship 'author' between objects in different contexts
Upvotes: 1
Views: 72
Reputation: 1494
If I'm not mistaken but the AppDelegate persistentContainer.viewContext is a singleton. You shouldn't pass the MOC across threads the way you are trying to do.
Take a look at the apple documentation: https://developer.apple.com/documentation/coredata/using_core_data_in_the_background
TRY (not tested):
let pContext = persistentContainer.newBackgroundContext()
pContext.perform {
let user = pContext.fetch(<fetch Request>).first
let userObjcID = user.objectID
pContext.performAndWait {
let book = pContext.fetch(<another fetch request>).first
book.name = "skjkjd"
// pContext.save()
book.author = pContext.object(with: userObjcID)
pContext.save()
}
}
Upvotes: 1