Swift Core Data正在保存到/ dev / null,因此它仅在内存中

时间:2018-09-20 20:25:55

标签: swift core-data

我将Swift 4和NSPersistentContainer用于一个非常简单的数据模型。我有1个实体和几个属性加一个索引。 当我第一次创建此应用时,该应用将数据保存在真实存储中。然后,我添加了一个属性以及自动迁移的索引和设置。 现在,CoreData调试输出向我显示: CoreData:批注:连接到“ / dev / null”处的sqlite数据库文件 因此,我的数据不会在会话之间保存。 有没有办法指定sqlite db文件? 我可以回到旧文件吗?

var dataContainer: NSPersistentContainer = {
  let container = NSPersistentContainer(name: "MyProject")
  // Auto migrate data to new version
  let description = NSPersistentStoreDescription()
  description.shouldMigrateStoreAutomatically = true
  description.shouldInferMappingModelAutomatically = true
  container.persistentStoreDescriptions = [description]

  container.loadPersistentStores(completionHandler: { (storeDescription, error) in
  if let error = error {
    let msg = "\(error)"
    os_log("dataContainer: loadPersistentStores Error = %@", msg)
  }
  })
  container.viewContext.name = "MyProject"
  return container
}()

2 个答案:

答案 0 :(得分:2)

实例化NSPersistentStoreDescription时,可以选择传入URL。这是documentation的链接,而这里是该主题的a well explained post

let container = NSPersistentContainer(name: "NameOfDataModel")

let storeURL = try! FileManager
        .default
        .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("NameOfDataModel.sqlite")

let storeDescription = NSPersistentStoreDescription(url: storeURL)
container.persistentStoreDescriptions = [storeDescription]

答案 1 :(得分:0)

由于要使用默认的DataModel名称(即storeURL)创建"NameOfDataModel",因此无需使用"NameOfDataModel.sqlite"来显式创建FileManager-作为{ {1}}默认情况下将创建相同的内容。

因此,您可以利用默认的container位置(即"NameOfDataModel.sqlite")来创建URL实例,如下所示:

storeDescription


PS::由于上述迁移标志/键的默认值let container = NSPersistentContainer(name: "NameOfDataModel") if let storeURL = container.persistentStoreDescriptions.last?.url { let storeDescription = NSPersistentStoreDescription(url: storeURL) // Setting Migration Flags storeDescription.shouldMigrateStoreAutomatically = true storeDescription.shouldInferMappingModelAutomatically = true container.persistentStoreDescriptions = [storeDescription] } ,因此这一切可能都不过分。

文档:
shouldInferMappingModelAutomatically
shouldMigrateStoreAutomatically

相关问题