將 Xcode 更新到 13.4 后,我的核心資料持久性堆疊開始在 SwiftUI 預覽和 Xcode 單元測驗中失敗。
錯誤資訊:
Unresolved error Error Domain=NSCocoaErrorDomain Code=134081 "(null)" UserInfo={NSUnderlyingException=Can't add the same store twice}, ["NSUnderlyingException": Can't add the same store twice ...
持久性堆疊:
struct PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "Persistence")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
let description = NSPersistentStoreDescription()
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions.append(description)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
}
SwiftUI 預覽的用法:
struct MyScreen_Previews: PreviewProvider {
static var previews: some View {
MyScreen()
.environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
支持 SwiftUI 預覽的擴展:
extension PersistenceController {
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
// Pre-fill core data with required information for preview.
}
}
uj5u.com熱心網友回復:
您的代碼中有一個錯誤,當您附加到描述陣列時,您現在有 2 個描述。
將其更改為:
let description = container.persistentStoreDescriptions.first!
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
// Load
uj5u.com熱心網友回復:
我注意到,在加載持久性存盤后會產生錯誤。對于 SwiftUI 預覽和單元測驗,可以忽略此錯誤(不能兩次添加相同的商店)。
要忽略此類錯誤,需要檢查行程資訊中的XCTestSessionIdentifier和XCODE_RUNNING_FOR_PREVIEWS。
if let error = error as NSError? {
if ProcessInfo.processInfo.environment["XCTestSessionIdentifier"] == nil &&
ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == nil {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/485215.html
標籤:迅速 单元测试 核心数据 迅捷 swiftui-预览
上一篇:在反應中測驗減速器開關內的條件
下一篇:在js中添加迄今為止的月份
