Swift Core Data 正在保存到 /dev/null 所以它只在内存中

Nie*_*sma 5 core-data swift

我将 Swift 4 和 NSPersistentContainer 用于一个非常简单的数据模型。我有 1 个实体和几个属性以及一个索引。当我第一次创建这个应用程序时,它正在将数据保存在一个真实的商店中。然后我添加了一个属性以及索引和设置以自动迁移。现在 CoreData 调试输出向我显示: CoreData: annotation: Connecting to sqlite database file at "/dev/null" 因此,我的数据不会在会话之间保存。有没有办法指定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
}()
Run Code Online (Sandbox Code Playgroud)

se_*_*dev 7

当您实例化您的 NSPersistentStoreDescription 时,您可以选择传入一个 URL。这是文档的链接,这是有关该主题的详细解释的帖子

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]
Run Code Online (Sandbox Code Playgroud)