Separating CoreData functionality from the View (SwiftUI) but Still with observability

Without having to use @FetchRequest at the View level has any been able to successfully implement a CoreData Stack with observability in a model with the model being used at the View level. The view model sits between the View & Coredata Stack

CoreData Stack

ViewModel (ObservableObject)

SwiftUI View

Answered by DelawareMathGuy in 701173022

hi,

your ViewModel simply needs to use an NSFetchedResultsController to hook into Core Data, and keep the array of Core Data objects that you would ordinarily define in the View (using @FetchRequest) as a @Published property. whenever the resultsController fires, update the array property.

be sure your View keeps a reference to the ViewModel as an @ObservedObject.

hope that helps,

DMG

Accepted Answer

hi,

your ViewModel simply needs to use an NSFetchedResultsController to hook into Core Data, and keep the array of Core Data objects that you would ordinarily define in the View (using @FetchRequest) as a @Published property. whenever the resultsController fires, update the array property.

be sure your View keeps a reference to the ViewModel as an @ObservedObject.

hope that helps,

DMG

@DelawareMathGuy this is what I had to do to trigger the FRCDelegate but this goes against the FRC automatically doing it after the performFetch

fetchedResultsController?
                .publisher(for: \.fetchedObjects)
                .receive(on: OperationQueue.main)
                .sink(receiveValue: { [weak self] data in
                    guard let self = self,
                            let data = data else { return }
                    for (index, object) in data.enumerated() {
                        let indexpath = IndexPath(item: index, section: 0)
                        if let controller = self.fetchedResultsController as? NSFetchedResultsController<NSFetchRequestResult> {
                            self.controller(controller, didChange: object,
                                            at: nil,
                                            for: .insert,
                                            newIndexPath: indexpath)
                        }
                    }
                }).store(in: &cancellables)
Separating CoreData functionality from the View (SwiftUI) but Still with observability
 
 
Q