Post

Replies

Boosts

Views

Activity

Reply to Using Core Data with SwiftUI App Protocol
@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.
Jun ’20
Reply to Using Core Data with SwiftUI App Protocol
@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) }
Jun ’20