如何NSKeyedUnarchive NSManagedObject的子类导入到Core Data? [英] How to NSKeyedUnarchive subclasses of NSManagedObject to import into Core Data?

查看:119
本文介绍了如何NSKeyedUnarchive NSManagedObject的子类导入到Core Data?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现有的基于文档的应用程序使用 NSKeyedArchiver / NSKeyedUnarchiver 保存并加载其数据,目前已转换为使用Core数据作为它的存储后端。

An existing document based application that saves and loads it's data using NSKeyedArchiver/NSKeyedUnarchiver is currently transformed to use Core Data as it's storage backend.

现在我试图有一种导入使用以前的应用程序保存的文件。对象结构没有改变,但我改变所有对象为 NSManagedObject s。现在 initWithCoder:调用 [super initWithCoder:] ,并且不使用 NSEntityDescription 。这是失败(如预期)。

Now I am trying to have a kind of import of files saved using the former application. The object structure didn't change, but I changed all objects to be NSManagedObjects. Now the initWithCoder: calls [super initWithCoder:] and doesn't create the object using NSEntityDescription. That failes epically (as expected).

我的问题是:有什么最佳实践/好建议有这样的导入功能?

My question is: what is the best practice / a good advice to have such an import functionality?

推荐答案

正确的方法是实现 NSAtomicStore 的子类,将旧数据格式解包到Core Data表示中。使用该存储加载旧数据后,您可以使用 - [NSPersistentStoreCoordinator migratePersistentStore:toURL:options:withType:NSSQLiteStoreType错误:] 轻松迁移数据

The correct way would be to implement a subclass of NSAtomicStore that unarchives the old data format into a Core Data representation. After loading the old data using that store, you can easily migrate the data using -[NSPersistentStoreCoordinator migratePersistentStore:toURL:options:withType:NSSQLiteStoreType error:]

OLD(WRONG)ANSWER:

将我自己的解决方案我发现了心理学院描述的相同的解决方案:

After fiddeling together my own solution (with some banging-head-on-desk involved) I found the same solution described by The Mental Faculty:

KEYED-ARCHIVING TO CORE DATA MIGRATION

他们做,但我创建了我自己的子类 NSKeyedValueDecoder ,存储上下文。所有实体的 initWithCoder:对我的 CBManagedObject 超类看起来像这样:

I did it the same way they do, but I created my own subclass of NSKeyedValueDecoder that stores the context. The initWithCoder: of my CBManagedObject superclass to all entities looks like this:

- (id) initWithCoder:(NSCoder *)inCoder {
    NSManagedObjectContext *context = ((CBNSKeyedUnarchiverCoreData*)inCoder).context;
    self = [super initWithEntity:[NSEntityDescription entityForName:[[self class] entityName] 
                                             inManagedObjectContext:context] insertIntoManagedObjectContext:context];
    if (!self) return nil;
    return self;
}

每个实体给他的实体名称加上类方法 + entityName

Each entity gives his entity name with the class method +entityName.

似乎是一个很好的解决方案,因为它现在工作非常好。

Seems like a good solution as it works very good by now.

这篇关于如何NSKeyedUnarchive NSManagedObject的子类导入到Core Data?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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