在哪里放置 persistentStoreDescriptions ?在 Swift3 Coredata 样板堆栈
Posted
技术标签:
【中文标题】在哪里放置 persistentStoreDescriptions ?在 Swift3 Coredata 样板堆栈【英文标题】:where to put persistentStoreDescriptions ? in Swift3 Coredata Boilerplate Stack 【发布时间】:2017-04-15 17:09:04 【问题描述】:我将我的 Coredata 迁移到了新版本,并放置了 persistentStoreDescriptions 在 loadPersistentStores 和应用程序不会崩溃但不会持久化数据之前,考虑到它在迁移之前运行良好,这是我的代码:
lazy var persistentContainer: NSPersistentContainer =
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreTest3")
let description = NSPersistentStoreDescription()
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions = [description]
container.loadPersistentStores(completionHandler: (storeDescription, error) in
if let error = error as NSError?
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
)
return container
()
【问题讨论】:
【参考方案1】:根据文档,您必须在初始化持久存储描述时指定托管对象模型的 URL:
let description = NSPersistentStoreDescription(url: storeURL)
要获取 URL,请查看Bundle.URL(forResource:withExtension)
【讨论】:
谢谢我在看到你的答案之前找到它这是我提出的确切问题:let urlStore = directory.appendingPathComponent("MYAPPName.sqlite") description.url = urlStore 顺便说一句,谢谢这是答案,太好了,挣扎 3 或 4 天 我遇到了同样的问题,似乎无法让这部分正常工作。 @flu 评论中的directory
是什么?以上是关于在哪里放置 persistentStoreDescriptions ?在 Swift3 Coredata 样板堆栈的主要内容,如果未能解决你的问题,请参考以下文章