【发布时间】:2018-08-12 14:14:57
【问题描述】:
我尝试在我的应用程序中预加载我的数据库(.sqlite、.sqlite-wal 和 .sqlite-shm),但我不能。
我试试这个:
func preloadDBData()
{
let sqlitePath = Bundle.main.path(forResource: "leksikonPreload", ofType: "sqlite")
let sqlitePath_shm = Bundle.main.path(forResource: "leksikonPreload", ofType: "sqlite-shm")
let sqlitePath_wal = Bundle.main.path(forResource: "leksikonPreload", ofType: "sqlite-wal")
let URL1 = URL(fileURLWithPath: sqlitePath!)
let URL2 = URL(fileURLWithPath: sqlitePath_shm!)
let URL3 = URL(fileURLWithPath: sqlitePath_wal!)
let URL4 = URL(fileURLWithPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/leksikonPreload.sqlite")
let URL5 = URL(fileURLWithPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/leksikonPreload.sqlite-shm")
let URL6 = URL(fileURLWithPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/leksikonPreload.sqlite-wal")
if !FileManager.default.fileExists(atPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/leksikonPreload.sqlite") {
// Copy 3 files
do {
try FileManager.default.copyItem(at: URL1, to: URL4)
try FileManager.default.copyItem(at: URL2, to: URL5)
try FileManager.default.copyItem(at: URL3, to: URL6)
print("=======================")
print("FILES COPIED")
print("=======================")
} catch {
print("=======================")
print("ERROR IN COPY OPERATION")
print("=======================")
}
} else {
print("=======================")
print("FILES EXIST")
print("=======================")
}
}
并在我的 appDelegate didFinishLaunchingWithOptions 方法中调用 preloadDBData()。我的核心数据模型的名称:“leksikon”,我的预加载数据的名称:“leksikonPreload”。当“文件已复制”和“文件存在”时,此函数工作正常,并且真正写入,但是当我尝试打印我的数据时 - 我的数组包含 0 个元素,但我确信 leksikonPreload 包含 12 个值。 我的打印代码:
func printData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest: NSFetchRequest<Word> = Word.fetchRequest()
do
{
let arr = try context.fetch(fetchRequest)
for obj in arr {
print(obj.engValue)
print(obj.rusValue)
print(obj.was)
}
}
catch
{
print(error.localizedDescription)
}
}
【问题讨论】:
-
如何在应用委托中初始化持久化容器?默认情况下,它会为模型和商店使用项目名称:您可能需要指定不同的商店名称(除非您的项目称为 leksikonPreload?)