I'm writing an application using the MVVM
pattern. And I'm wondering know how to create the CoreData
stack so it can be accessed from various places in my app.
First approach is to create a persistent container in the AppDelegate
and then inject this service to my ViewModels (simultaneously passing the managedObjectContext
as an environment variable to my Views).
This way, however, accessing context throughout the app is more difficult: e.g. in decoding network responses, as they don't have access to the managedObjectContext
:
protocol APIResource {
associatedtype Response: Decodable
...
}
extension APIResource {
func decode(_ data: Data) -> AnyPublisher<Response, APIError> {
Just(data)
// how can I access context here to pass it to JSONDecoder?
.decode(type: Response.self, decoder: JSONDecoder())
.mapError { error in
.parsing(description: error.localizedDescription)
}
.eraseToAnyPublisher()
}
}
The other solution I've seen is to use a singleton. I can access it from anywhere in the project but how can I create it in the right way?
What if I wan't to modify some object in the main and the background queue at the same time? Or what if both queues want to modify the same object?