这可能是一个很长的答案。最好将其解释为教程。以下链接将向您展示该怎么做。
http://www.appcoda.com/core-data-preload-sqlite-database/
我发现文章/教程的开头和结尾对您尝试做的事情很有用。
我最近将数据预加载到一个测验的应用程序中,使用单独的 Xcode 模拟器来创建所需的 3 个 SQLite 文件。这篇文章将向您展示如何找到它们,如何将它们“捆绑”到您想要“预加载”的 Xcode 项目中,并将告诉您代码在您的“AppDelegate.swift”文件中添加。
有 3 件事可以帮助您在完成项目时避免问题...
确保您在模拟器(独立项目)中创建的数据的实体和属性名称(在您的数据模型(核心数据)中)与项目中的相同你想“预加载”。 [否则预加载不会工作]
添加到 'AppDelegate.swift' 中的代码旨在指导您的应用程序将预加载数据转到何处(请参阅随附的教程),但是,我发现我需要调整代码以使其工作...(如下所述)
没有从 'AppDelegate.swift' 文件中删除任何内容,只是添加了 3 个 SQLite 文件的名称...例如
在 Core Data 堆栈的“AppDelegate.swift”中...您会发现...
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("EoMQ", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
别管这个,但直接在下面你需要有以下代码......
// ---------------------------------------------------
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Q100cdCoreData.sqlite") // originally = "SingleViewCoreData.sqlite" - then changed to new name... from imported sqlite files
// ---------------------------------------------------
// ** Load the Already made DB from Simulator **
if !NSFileManager.defaultManager().fileExistsAtPath(url.path!) {
let sourceSqliteURLs = [NSBundle.mainBundle().URLForResource("Q100cdCoreData", withExtension: "sqlite")!, NSBundle.mainBundle().URLForResource("Q100cdCoreData", withExtension: "sqlite-wal")!, NSBundle.mainBundle().URLForResource("Q100cdCoreData", withExtension: "sqlite-shm")!]
let destSqliteURLs = [self.applicationDocumentsDirectory.URLByAppendingPathComponent("Q100cdCoreData.sqlite"), self.applicationDocumentsDirectory.URLByAppendingPathComponent("Q100cdCoreData.sqlite-wal"), self.applicationDocumentsDirectory.URLByAppendingPathComponent("Q100cdCoreData.sqlite-shm")]
for index in 0 ..< sourceSqliteURLs.count {
do {
try NSFileManager.defaultManager().copyItemAtURL(sourceSqliteURLs[index], toURL: destSqliteURLs[index])
} catch {
print(error)
}
}
}
我在模拟器中创建的 3 个文件名为“Q100cdCoreData”,但具有三种不同的扩展名... (a) .sqlite (b) .wal (c) .shm
但是你需要通过教程并理解这个过程。