2017-09-05 115 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 { ... }