SQLite到核心数据迁移

时间:2016-08-10 07:10:30

标签: ios objective-c swift sqlite core-data

我在App Store上有一个使用 SQLite 作为数据库的实时应用程序,现在我想在App中实现 Core Data 的下一次更新,从.sqlite加载所有数据文件没有破坏应用程序。我一直在阅读教程,但它没有多大帮助。我不知道如何继续。请指出正确的方向。

4 个答案:

答案 0 :(得分:3)

来自核心数据documentation

  

如何将现有的SQLite数据库与Core Data一起使用?

     

除非将现有的SQLite数据库导入到   核心数据存储。虽然Core Data支持SQLite作为其中之一   持久存储类型,数据库格式是私有的。你不能   使用本机SQLite API创建SQLite数据库并使用它   直接使用Core Data。如果您有现有的SQLite数据库,那么   需要将其导入Core Data存储区。另外,不要   使用本机操作现有的Core Data创建的SQLite存储   SQLite API

您可以尝试使用https://github.com/tapasya/Sqlite2CoreData工具,但它似乎已经过时了。

答案 1 :(得分:2)

我认为@SaintThread在这里遇到了主要问题。原因是Core Data不是SQLite的包装器 - 它是一个不同的API,具有不同的假设,恰好在内部使用SQLite。如果您自己使用SQLite,Core Data不会尝试与您使用SQLite的方式兼容。

也就是说,如果您仍想迁移,则必须设计Core Data模型,然后编写完全自定义代码以从现有SQLite文件迁移到Core Data。您的代码需要从SQLite读取所有内容,将其转换为新的Core Data表示,保存更改,然后删除现有的SQLite文件。

删除现有的SQLite文件时,请务必同时删除SQLite日志文件(如果有)。

答案 2 :(得分:1)

困难主要取决于您的代码体系结构的设置情况。这样做没有简单的程序...... 如果相当简单,将Core数据添加到项目中,理解它是另一回事。

以下是您可能需要注意的一些事项:

  • CoreData以自己的方式创建sqlite文件,这意味着你无法提供任何.sqlite文件并希望最好。您必须让CoreData创建自己的文件,并将数据从sqlite存储转移到核心数据。

  • 你的表变成了类(就像在大多数ORM中一样,它被称为实体)并且你不能直接实例化一个新的实体,这意味着如果你有一个表Employee,你不能做Employee * john = [[Employee alloc]在里面];那不行!插入元素是NSEntityDescritpion类的责任。因此,请检查您的代码是否存在错误......

如果核心数据有点复杂,那么Realm是一个很好的ORM选择:https://realm.io/products/objc/

祝你好运......

答案 3 :(得分:0)

以下是我找到最佳工作方式;但请确保在抛出时使用良好的错误处理。

这是Apple的原创方式:

https://developer.apple.com/library/content/samplecode/CoreDataBooks/Listings/Classes_CoreDataBooksAppDelegate_m.html#//apple_ref/doc/uid/DTS40008405-Classes_CoreDataBooksAppDelegate_m-DontLinkElementID_8

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataBooks.CDBStore"];

/*
 Set up the store.
 For the sake of illustration, provide a pre-populated default store.
 */
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn't exist, copy the default store.
if (![fileManager fileExistsAtPath:[storeURL path]]) {
    NSURL *defaultStoreURL = [[NSBundle mainBundle] URLForResource:@"CoreDataBooks" withExtension:@"CDBStore"];
    if (defaultStoreURL) {
        [fileManager copyItemAtURL:defaultStoreURL toURL:storeURL error:NULL];
    }
}

NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption: @YES, NSInferMappingModelAutomaticallyOption: @YES};
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

NSError *error;
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {

...

这些是新方式 - Xcode8

Swift 3 preload from SQL files in appDelegate

Core Data with pre-filled .sqlite (Swift3)

Why does not copy database.db from bundle to document directory in swift 3?

https://www.raywenderlich.com/145877/core-data-tutorial-multiple-managed-object-contexts-2

相关问题