Unexpected Core Data Multithreading Violation
It is recommended to avoid using the .performAndWait
API, to be used only at the rarest of the rare occasions, when everything else has failed!
Evaluate morphing Context.current
to managedObjectContext.perform
throughout the application.
The effect of this change would be addition of asynchronicity in all your database operations.
It may sound of a massive change to ask for but trust me, just decide to treat Core Data as a completely asynchronous API & life will be much better this way.
I'm sure the current crash you are facing is a result of compound result of the corrupted behavior of .performAndWait
Check out this blog to get better understanding of multithreading in Core Data
Storing the "current" background context in a global state is a bad practice. I can't point out where exactly in your code it is messing up, but unexpected things can happen with global state when multithreading is involved. Change your find
function to accept a context
as a parameter. This will avoid using any global state and is will likely fix your problem.