Search code examples
ioscore-datamagicalrecord

Magical Record: crash when fetching data in background thread


I have a random crash when i perform MR_findFirstWithPredicate in a background (not main) thread. I am using NSManagedObjectContext.MR_defaultContext() for all magical record operations on both main and background threads - i think this is the root of the problem, but i am not sure how to fix it.

Should i use some other context when i perform operations in background threads? I tried using NSManagedObjectContext.MR_context but all fetches returned nil. Also tried NSManagedObjectContext.MR_newPrivateQueueContext but app crashed on each fetch operation.


Solution

  • You are correct, you should be using a context that is NSPrivateQueueConcurrencyType to do background. Sounds like the MR_newPrivateQueueContext is the correct call, but you probably you will have to give it a persistent Store or a parentContext. In this case you could set the MR_newPrivateQueueContext parentContext to the defaultContext

    let defaultContext = NSManagedObjectContext.MR_defaultContext()
    let privateContext = NSManagedObjectContext.MR_newPrivateQueueContext
    privateContext.parentContext = defaultContext