2016-08-10 193 views
1

我有它使用的SQLite 数据库,现在不会破坏应用程序的下一个更新我想在应用程序加载到执行核心数据从.sqlite文件的所有数据的App Store的现场应用。我一直在阅读教程,但没有多大帮助。我不知道如何继续。请指点我正确的方向。的SQLite到核心数据迁移

+0

为什么呢?你认为你会得到什么好处?现有的SQL解决方案是否正常工作?有什么不能做的吗? – Wain

回答

2

从核心数据documentation

如何使用现有的SQLite数据库核心数据?

除非将现有的SQLite数据库导入 核心数据存储区,否则您不这样做。虽然Core Data支持SQLite作为其持久存储类型之一,但数据库格式是私有的。你不能用 创建一个使用原生SQLite API的SQLite数据库,并直接在核心数据中使用它 。如果您有一个现有的SQLite数据库,您需要将其导入到Core Data存储中。此外,不要 使用原生 SQLite的API

您可以使用该工具https://github.com/tapasya/Sqlite2CoreData尝试操作一个现有的核心数据创建的SQLite的商店,但它似乎相当过时。

1

难度主要取决于您的代码架构设置得如何。没有简单的程序来做到这一点...... 如果相当简单,将Core数据添加到项目中,理解它是另一回事。

这里,你可能要注意几件事:

  • CoreData以自己的方式创建sqlite的文件,这意味着你不能给它任何.sqlite文件,并希望最好的。您将不得不让CoreData创建自己的文件,并将数据从sqlite存储转移到核心数据。

  • 你的表成为类(就像在大多数ORM中,它被称为实体),你不能直接实例化一个新的实体,这意味着如果你有一个表Employee,你不能这样做Employee * john = [[Employee alloc] init ]。那不会!插入元素是NSEntityDescritpion类的职责。因此,检查你的可能的错误代码,有...

如果核心数据是有点复杂的,境界是一个很好的替代ORM:https://realm.io/products/objc/

好运...

2

我想@SaintThread在这里遇到了主要问题。其原因是Core Data不是SQLite的包装 - 它是一个不同的API,它有不同的假设,恰好在内部使用SQLite。如果你自己使用SQLite,核心数据不会与你如何使用SQLite兼容。这就是说,如果你仍然想迁移,你将不得不设计一个核心数据模型,然后编写完全自定义的代码从现有的SQLite文件迁移到核心数据。您的代码需要从SQLite读取所有内容,将其转换为新的Core Data表示,保存更改,然后删除现有的SQLite文件。

删除现有SQLite文件时,请确保也删除SQLite日记文件(如果有)。

0

以下是我找到工作最好的方式;但请确保您在投掷中使用良好的错误处理。

这是来自苹果的原始的方式:

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