简体   繁体   中英

iPhone programming - Background saving with core data

I am trying to save data into core data in the background thread, as it takes quite some time to save.

I did:

[self performSelectorInBackGround:@selector(insertRecord:) withObject:data];

When all works fine until the line in insertRecord Method hits contextsave:&error . Program received signal : "SIGABRT"

Am I doing anything wrong? it works ok when its in main thread, I just move the codes to another method and run it in background and it doesn't work anymore.

According to the "Concurrency with Core Data" section of Core Data Programming Guide :

The pattern recommended for concurrent programming with Core Data is thread confinement: each thread must have its own entirely private managed object context.

and

Using thread confinement, you should not pass managed objects or managed object contexts between threads.

It looks like you're passing a managed object to the background thread, which is forbidden. I don't know if you're also trying to share your managed object context between threads.

That document describes a couple of workarounds for passing managed objects to other threads. You'll need to implement one of them.

The problem here is that managed object contexts aren't thread-safe. If your -insertRecord: method uses the main thread's managed object context, you're asking for trouble.

The blog Cocoa Is My Girlfriend has an article, Core Data and Threads, Without the Headache on this very topic and suggests some strategies for saving in the background. The basic idea is to make changes on a context that belongs to a background thread, and then merge the changes into the main thread's context. That gives you an up-to-date context that you can save in the background while still keeping the main thread's context current.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM