核心数据多线程应用程序 [英] Core Data multi thread application

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

问题描述

我试图以多线程方式使用核心数据。
我只想在后台下载新数据的同时使用之前下载的数据显示应用程序。
这应该让用户在更新过程中访问应用程序。



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



问题是创建新对象在旧的同一上下文中显示它可以抛出BAD_INSTRUCTION异常。
所以,我决定为新数据使用一个单独的上下文,但是我不能想出一种方法,在完成后将所有对象移动到其他上下文。



Paolo aka SlowTree

解决方案

Apple并发核心数据文档是开始。阅读它真的仔细...我被误解了很多次。



基本规则是:



<
  • 每个程序使用一个 NSPersistentStoreCoordinator

  • 每个线程创建一个 NSManagedObjectContext


  • 不要将 NSManagedObject 传递给另一个主题。


    更多规则:


    1. 确保在获取对象ID之前将对象保存到商店中。

    2. 如果您从多个线程更改托管对象,请注意合并策略。

    3. NSManagedObjectContext -mergeChangesFromContextDidSaveNotification:

    但让我重复一遍,请仔细阅读文件!这真的很值得!


    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.

    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.

    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.

    Paolo aka SlowTree

    解决方案

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

    Basic rules are:

    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.

    More rules:

    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!

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

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