我正在使用以下代码设置我的应用程序持久容器:
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "App_Name")
let myFileManager = FileManager()
do {
let docsurl = try myFileManager.url(for:.applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myUrl = docsurl.appendingPathComponent("App_Name")
let description = NSPersistentStoreDescription(url: myUrl)
container.persistentStoreDescriptions = [description]
let options = [NSInferMappingModelAutomaticallyOption : true,
NSMigratePersistentStoresAutomaticallyOption : true]
try container.persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: myUrl, options: options)
} catch {
fatalErrorText = error.localizedDescription
print(fatalErrorText)
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalErrorText = error.debugDescription
print(fatalErrorText)
}
})
return container
}()
但是,当我尝试访问核心数据时,出现以下错误:
2017-08-07 14:43:57.391529 + 0100应用程序名称[98764:1854740] [错误]错误:-addPersistentStoreWithType:SQLite配置:(空)URL:file:///Users/Seb/Library/Developer/CoreSimulator /Devices/241E1A36-631B-4071-8357-5F551F32403F/data/Containers/Data/Application/BC35D1CD-FA17-4F1F-99A0-EB0E73A42F3C/Library/Application%20Support/App_Name.sqlite 选项:{ NSInferMappingModelAutomaticallyOption = 1; NSMigratePersistentStoresAutomaticallyOption = 1; } ...返回错误Error Domain = NSCocoaErrorDomain Code = 134080“(null)”UserInfo = {NSUnderlyingException =无法使用userInfo字典添加同一商店两次} { NSUnderlyingException = "不能两次添加同一商店"; } CoreData:错误:-addPersistentStoreWithType:SQLite配置:(空)URL:file:///Users/Seb/Library/Developer/CoreSimulator/Devices/241E1A36-631B-4071-8357-5F551F32403F/data/Containers/Data/Application/ BC35D1CD-FA17-4F1F-99A0-EB0E73A42F3C/Library/Application%20Support/App_Name.sqlite 选项:{ NSInferMappingModelAutomaticallyOption = 1; NSMigratePersistentStoresAutomaticallyOption = 1; } ...返回错误Error Domain = NSCocoaErrorDomain Code = 134080“(null)”UserInfo = {NSUnderlyingException =Can't添加同一商店两次}与userInfo字典{ NSUnderlyingException = "不能两次添加同一个商店"; }
我已启用 iCloud,并且确实找到了一个声称问题出在 iCloud 的答案,但他们的解决方案对我不起作用。
我在这里找到了这个问题的一些其他解决方案,但无法破译/翻译答案。
A
NSPersistentContainer
是核心数据堆栈所需的所有内容的包装器。它将创建一个带有 persistenceStoreCoordinator 设置和单个 sql 存储的 ManagedObjectContext。可以简化地查找具有您指定的名称的模型,并使用相同的名称命名 sql 文件。默认情况下,自动迁移处于开启状态 NSPersistentContainer
。
如果您需要更多自定义设置,您可以自己创建所有实体(这并不难)。或者您可以在调用
persistentStoreDescriptions
之前设置 loadPersistentStores
属性。通过 persistenceStoreDescription,您可以设置保存 sql 文件的 URL,并设置 shouldMigrateStoreAutomatically
。
一般来说,没有理由这样做,因为默认情况下它设置为 true,请参阅 https://developer.apple.com/documentation/coredata/nspersistentstoredescription/1640566-shouldmigratestoreautomatically
TL;DR 删除 do catch 中的所有内容,
loadPersistentStores
的默认行为将正常工作。