I'm currently learning SwiftUI to further include it in my daily UIKit-based workflow. I got to a point where I can not get a concept running in SwiftUI, that I've been using for years in UIKit.
The idea is to use a child context of my main CoreData managedObjectContext for editing entities. I implement it quite basically by doing the following:
// Get view context of application
let viewContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Create NSManagedObjectContext
let editingContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
// Set the parent of the editing context to the main view context
editingContext.parent = viewContext
By using a separate editingContext I can make changes to an entity in it without the change proceeding directly to my main context. If the user chooses to abort the change, I just reset the editingContext.
For the implementation in SwiftUI, I chose to implement the editingContext as an environment object by creating a custom EnvironmentKey:
struct EditingContextKey: EnvironmentKey {
static let defaultValue: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
}
extension EnvironmentValues {
var editingContext: NSManagedObjectContext {
get {
return self[EditingContextKey.self]
}
set {
self[EditingContextKey.self] = newValue
}
}
}
Then the editingContext is added to my root view:
let contentView = ContentView()
.environment(\.managedObjectContext, viewContext)
.environment(\.editingContext, editingContext)
To this point everything works fine. I also can use the editingContext by calling the following in the respective view.
@Environment(\.editingContext) var editingContext
However, as soon as I make changes to the entity in the editingContext and try to save the editingContext, I get an unexpected error:
Fatal error: Unresolved error Error Domain=Foundation._GenericObjCError Code=0 "(null)", [:]: file
I did already checked, if the context of the edited entity is matching the editingContext. This seems to be the case. I have the feeling, it could have something to do with a binding in SwiftUI, but have no idea how to approach finding a solution.
Has anyone had a similar problem? Or is my basic approach to the desired functionality wrong and there is a more convenient way of doing this?
Thank you!