Thanks @espen. I hope a fix soon :/
Post
Replies
Boosts
Views
Activity
@ryanbdevilled Yes, you can. This pattern is used by Apple in their libraries such as NotificationCenter.default (->"default" is the singleton), DispatchQueue.main (->main is the singleton), UserDefaults.standard (->standard is the singleton).
This pattern helps to have a single instance of an object shared across all your app. And of course you can code another functions in order to help your persistentObject, like func saveContext(), func deleteAll(), etc. The possibilities are infinity.
I use this pattern to have 1 record of entity shared across all my app, this way:
final class PersistentStore: ObservableObject {
@Published var patient: Patient
init(patientUUID: UUID) {
/* Fetch request, get the patient with that UUID, etc
... */
}
func changePatient(to: UUID) {
}
}
And whenever that patient changes all my SwiftUI views that are observing the "patient" variable reloads automatically. If you want reload your conventional UIKit/AppKit views you can do this also:
var cancellableBag = Set<AnyCancellable>()
override func viewDidLoad {
PersistentStore.shared.patient.objectWillChange.sink { _in
reloadView() /* Or other implementations of what you want to do */
}.store(in: &cancellableBag)
}
@davextreme You don't need AppDelegate to instantiate the persistentContainer in SwiftUI, as he explained. And in my last response you can get the solution for get viewContext working elsewhere in your app (with singleton pattern).
I'm waiting for that too :/
@ryanbdevilled I'm doing that with singleton pattern (in order to access to persistent store from UIKit views).
final class PersistentStore {
let shared = PersistentStore()
lazy var persistentStore = { ... }
func saveContext() { ... }
}
var body: some Scene {
WindowGroup {
MovieList()
.environment(\.managedObjectContext, PersistentStore.shared)
}
}
It is important to call to PersistentStore.shared from anywhere in your app (because it is instantiated yet), not PersistentStore(). If you are calling that from SwiftUI views, obviously you can directly from @environmentObject.
Feedback sent!
Code: FB7808542
Same problem here. I think it is a bug.