Adding new version of core data model?
我刚刚创建了一个新版本的核心数据模型,其中包含一个额外的对象以及重新设计的关系。
我现在有两个文件,Medical_Codes.xcdatamodel 和 Medical_Codes_ 2.xcdatamodel。
我是否必须删除旧的 NSManagedObject 类文件并重新创建它们?
我必须更改我的持久存储代码吗?
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
– (NSManagedObjectModel *)managedObjectModel
{ if (__managedObjectModel != nil) { return __managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@“Medical_Codes” withExtension:@“mom”]; __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return __managedObjectModel; } – (NSPersistentStoreCoordinator *)persistentStoreCoordinator NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@“Medical_Codes.sqlite”]; NSFileManager *fileManager = [NSFileManager defaultManager]; if (!defaultStorePath) NSError *error = nil; if (![fileManager copyItemAtPath:defaultStorePath toPath:[storeURL path] error:&error]) NSError *error = nil; return __persistentStoreCoordinator; |
CoreData 提供了将数据库的旧模式迁移到新模式的各种级别。有时您可以进行轻量级迁移,这意味着您无需执行任何特殊操作,只需创建新模型并生成新的托管对象类。下次启动应用程序时,模型管理器会发挥作用,将旧数据迁移到新架构。
但是,当您的新模型与旧模型显着不同时,您需要创建一个模型映射文件,为 CoreData 提供必要的迁移信息以从旧模型映射到新模型。此映射模型文件由 Xcode 复制到您的包中,模型管理器使用它进行必要的迁移。
您还需要在运行时创建持久存储协调器期间传递一些附加选项(所以,是的,您必须稍微更改持久存储协调器代码)。有点像:
|
1
2 3 4 5 6 7 8 |
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) { |
所以,回答你的第一个问题。如果您添加了新的属性或关系,那么您将需要创建新的托管对象文件。如果您所做的只是修改有关预先存在的属性或关系的一些选项,那么您的旧托管对象文件仍然有效。
如果您还没有阅读过,您应该阅读 Apple 撰写的有关 CoreData 的所有内容。我还没有读过一本比他们的在线文档更好地涵盖该主题的书。特别是,阅读他们关于版本控制和迁移的信息。
- 我不知道这是否对乔恩有所帮助,但这是我见过的最好的答案。它绝对帮助我解决了我自己的迁移问题。
- 谢谢,我很欣赏你的赞美。我很高兴它帮助了某人。
- 必须同意 Apple 的 Core Data 文档很棒,特别是对于版本控制这个棘手的话题。
- 如果您要执行轻量级迁移,请注意一个非常重要的注意事项。确保不要在应用程序委托的”applicationDidFinishLaunching”方法中初始化迁移。如果数据库包含大量数据,迁移可能需要一些时间。并且 “didFinishLaunching” 方法带有一个隐式的时间限制。如果您的应用程序未在该限制内完成启动,它将被 iOS 终止。
- 链接坏了。这是一个更新的链接。 developer.apple.com/library/ios/documentation/Cocoa/Conceptu??al/…
来源:https://www.codenong.com/8541902/
