【问题标题】:NSPersistentContainer doesnt create database fileNSPersistentContainer 不创建数据库文件
【发布时间】:2017-09-05 15:48:17
【问题描述】:

我正在创建一个 NSPersistentContainer 来保存一些数据,但即使在上下文中调用 save() 也不会创建任何数据库文件。

我用于创建 NSPersistentContainer 的代码是:

let container = NSPersistentContainer(name: "Model")

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

container.persistentStoreDescriptions = [description]

container.loadPersistentStores { ... }

【问题讨论】:

    标签: ios swift database core-data


    【解决方案1】:

    我期待通过 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 { ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 2015-11-07
      • 1970-01-01
      • 2011-08-27
      • 2012-05-29
      相关资源
      最近更新 更多