gpt4 book ai didi

ios - NSPersistentContainer 不创建数据库文件

转载 作者:行者123 更新时间:2023-11-28 15:20:40 27 4
gpt4 key购买 nike

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

我用来创建 NSPersistentContainer 的代码是:

let container = NSPersistentContainer(name: "Model")

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

container.persistentStoreDescriptions = [description]

container.loadPersistentStores { ... }

最佳答案

我原以为通过 NSPersistentStoreDescription 设置自动迁移选项不会有问题,而且 Container 会使用默认的存储文件路径;但事实并非如此。

原来没有回退到默认路径,因此必须提供您自己的路径,这解决了问题:

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 { ... }

关于ios - NSPersistentContainer 不创建数据库文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46058968/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com