Andrew
Andrew

Reputation: 7883

MagicalRecord with NSOperation causing persistence issues

I'm using MagicalRecord to manage my core data. My app often receives chunks of data that needs iterated over then individually added to the store as records, and saved. I put this code into an NSOperation. It looks something like this:

class AddIncomingMessageOperation: NSOperation {
    override func main() {
        let context = NSManagedObjectContext.MR_context()

        self.message = Message.createMessage(
            json: self.messageJSON,
            context: context)
        if self.message != nil {
            context.MR_saveToPersistentStoreAndWait()
        }
    }
}

Running this on NSOperationQueue.mainQueue seems to work without issue, other than holding up the UI. But my next move is to run all of these operations on their own background operation queue. Adding them to this NSOperationQueue and running them then results in some mixed up data.

What I mean by this - my createMessage function checks for an existing Conversation object, and adds it to the conversation if it exists, or creates one if it doesn't. So it requires knowing what already exists in the store. What seems to be happening how, with them running on a background queue, is that they're creating conversations that have just been created in another operation.

I can solve all of this by setting operationQueue.maxConcurrentOperationCount = 1, but that obviously slows the whole thing down.

Upvotes: 0

Views: 92

Answers (1)

Mundi
Mundi

Reputation: 80273

You cannot use the main thread context on a background thread. Not in Core Data and not in Magical Record.

Use the MR methods designed for background operations, such as saveWithBlock. Create background contexts with MR_newContext.

If you make use of these simple APIs, you might be able to dispense with the cumbersome NSOperation subclasses.

Upvotes: 1

Related Questions