skip to Main Content

I’m trying to implement this solution: Combine, Publishers, and Core Data but I’m getting the following error:

enter image description here

Here is my implantation:

class DataModel: ObservableObject {
    @Published var customers: [Task] = []
    private var cancellables = Set<AnyCancellable>()

    init(viewContext: NSManagedObjectContext) {
        CDPublisher(request: Task.fetchRequest(),
                    context: viewContext)
            .sink(receiveCompletion: { _ in },
                  receiveValue: { value in
                   print("value: (value)")
                })
            .store(in: &cancellables)
    }
}

This is part of my view implementation:

import SwiftUI
struct ContentView: View {
    @Environment(.managedObjectContext) private var viewContext
    @FetchRequest(sortDescriptors: [])
    var dataModel: DataModel
    var task: FetchedResults<Task>
    init() {
        self.dataModel = DataModel(viewContext: viewContext)
    }
    var body: some View {

Any of you knows why I’m getting this error or what do I need to do to fix this error?

I’ll really appreciate your help

2

Answers


  1. Your @FetchedRequest should be of type FetchedResults<Result> Result should be whatever your entity name is from your Core Data model. Don’t get it confused for the attribute but the entity name. It can look like

    @FetchRequest(sortDescriptors: [])
    var dataModel: FetchedResults<Results> 
    
    Login or Signup to reply.
  2. Just remove the data model, @FetchRequest does it all for you.

    import SwiftUI
    
    struct ContentView: View {
    
        @Environment(.managedObjectContext) private var viewContext
        
        @FetchRequest(sortDescriptors: [])
        var tasks: FetchedResults<Task>
    
        var body: some View {
            ForEach(tasks) { task in
                TaskView(task: task)
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search