Core Data 多线程应用 [英] Core Data multi thread application

查看:15
本文介绍了Core Data 多线程应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以多线程方式使用核心数据.我只是想在后台下载新数据时显示具有先前下载数据的应用程序.这应该让用户在更新过程中访问应用程序.

I'm trying to use core data in a multi thread way. I simply want to show the application with the previously downloaded data while downloading new data in background. This should let the user access the application during update process.

我有一个 NSURLConnection,它使用委托异步下载文件(并显示进度),然后我使用 XMLParser 解析新数据并在单独的上下文中创建新的 NSManagedObjects,它有自己的persistentStore 并使用单独的线程.

I have a NSURLConnection which download the file asyncronously using delegate (and showing the progress), then i use an XMLParser to parse the new data and create new NSManagedObjects in a separate context, with its own persistentStore and using a separate thread.

问题是在旧对象的相同上下文中创建新对象同时显示它可能会引发 BAD_INSTRUCTION 异常.所以,我决定为新数据使用一个单独的上下文,但我无法找到一种方法,在完成后将所有对象移动到另一个上下文.

The problem is that creating new objects in the same context of the old one while showing it can throws BAD_INSTRUCTION exception. So, I decided to use a separate context for the new data, but I can't figure out a way to move all the objects to the other context once finished.

保罗又名慢树

推荐答案

Apple Concurrency with Core Data 文档 是起点.仔细阅读...我被我的误解咬了很多次!

The Apple Concurrency with Core Data documentation is the place to start. Read it really carefully... I was bitten many times by my misunderstandings!

基本规则是:

  1. 每个程序使用一个 NSPersistentStoreCoordinator.每个线程不需要它们.
  2. 为每个线程创建一个 NSManagedObjectContext.
  3. 永远不要将一个线程上的 NSManagedObject 传递给另一个线程.
  4. 相反,通过 -objectID 获取对象 ID,并将其传递给另一个线程.
  1. Use one NSPersistentStoreCoordinator per program. You don't need them per thread.
  2. Create one NSManagedObjectContext per thread.
  3. Never pass an NSManagedObject on a thread to the other thread.
  4. Instead, get the object IDs via -objectID and pass it to the other thread.

更多规则:

  1. 确保在获取对象 ID 之前将对象保存到商店中.在保存之前,它们是临时的,您无法从其他线程访问它们.
  2. 如果您从多个线程对托管对象进行更改,请注意合并策略.
  3. NSManagedObjectContext-mergeChangesFromContextDidSaveNotification: 很有帮助.
  1. Make sure you save the object into the store before getting the object ID. Until saved, they're temporary, and you can't access them from another thread.
  2. And beware of the merge policies if you make changes to the managed objects from more than one thread.
  3. NSManagedObjectContext's -mergeChangesFromContextDidSaveNotification: is helpful.

但是我再说一遍,请仔细阅读文档!真的很值得!

But let me repeat, please read the document carefully! It's really worth it!

这篇关于Core Data 多线程应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆