我正在使用该MVVM模式编写应用程序。我想知道如何创建CoreData堆栈,以便可以从我的应用程序的各个位置访问它。
第一种方法是在 中创建一个持久性容器AppDelegate,然后将此服务注入我的 ViewModel(同时将其managedObjectContext作为环境变量传递给我的视图)。
然而,通过这种方式,访问整个应用程序的上下文更加困难:例如,在解码网络响应时,因为他们无法访问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()
}
}
Run Code Online (Sandbox Code Playgroud)
我见过的另一个解决方案是使用单例。我可以从项目的任何地方访问它,但如何以正确的方式创建它?
如果我不想同时修改主队列和后台队列中的某个对象怎么办?或者如果两个队列都想修改同一个对象怎么办?