【发布时间】:2020-05-05 09:25:54
【问题描述】:
我在将 NSManagedObjectContext 暴露给 SwiftUI 的环境时遇到问题。这是我的代码:
extension SceneDelegate: UIWindowSceneDelegate {
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = scene as? UIWindowScene else { return }
let window = UIWindow(windowScene: windowScene)
let context = PersistentContainer.shared.viewContext
let rootView = TabBarView().environment(\.managedObjectContext, context)
window.rootViewController = UIHostingController(rootView: rootView)
self.window = window
window.makeKeyAndVisible()
}
}
class PersistentContainer: NSPersistentContainer {
static let shared = PersistentContainer()
private convenience init() {
self.init(name: "App")
viewContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyStoreTrumpMergePolicyType)
viewContext.automaticallyMergesChangesFromParent = true
loadPersistentStores { description, error in
if let error = error {
fatalError("Unable to load persistent stores: \(error)")
}
}
}
}
struct CategoriesView: View {
@Environment(\.managedObjectContext) var context
@FetchRequest(entity: CoreCategory.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \CoreCategory.createdAt, ascending: true)
]
) var categories: FetchedResults<CoreCategory>
}
我的CategoriesView 是我的根视图,因此在应用启动时会访问上下文。我的应用启动时出现以下错误...
[error] warning: View context accessed for persistent container App with no stores loaded
...但视图能够很好地显示结果。此外,如果我以与我的 CategoriesView 相同的格式呈现包含 SwiftUI @FetchRequest 的模态视图,应用程序将崩溃并出现以下错误:
[SwiftUI] Context in environment is not connected to a persistent store coordinator: <NSManagedObjectContext: 0x600002348b60>
从我在网上找到的所有教程中,我以推荐的方式公开我的NSManagedObjectContext。我有一种感觉,这与 loadPersistentStores 是异步的有关,但上下文是在 Environment 中同步设置的。还有其他人能够让 CoreData 在 SwiftUI 中工作吗?
【问题讨论】: