2017-09-05 107 views
0

我創建了一個NSPersistentContainer來保存一些數據,但即使在上下文中調用save()也不會創建任何數據庫文件。NSPersistentContainer不創建數據庫文件

我使用的用於創建NSPersistentContainer的代碼是:

let container = NSPersistentContainer(name: "Model") 

let description = NSPersistentStoreDescription() 
description.shouldInferMappingModelAutomatically = true 
description.shouldMigrateStoreAutomatically = true 

container.persistentStoreDescriptions = [description] 

container.loadPersistentStores { ... } 

回答

0

我期待的是通過NSPersistentStoreDescription設置自動遷移選項不會是一個問題,而容器將使用默認存儲文件路徑;但它沒有。

原來沒有回退到默認路徑,所以一個人必須要提供自己的路徑,它解決了這個問題:

let container = NSPersistentContainer(name: "Model") 

let dbURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!.appendingPathComponent("DB.sql") 
let description = NSPersistentStoreDescription(url: dbURL) 
description.shouldInferMappingModelAutomatically = true 
description.shouldMigrateStoreAutomatically = true 

container.persistentStoreDescriptions = [description] 

container.loadPersistentStores { ... }