0

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

user2924482
  • 8,380
  • 23
  • 89
  • 173

2 Answers2

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> 
Yotzin Castrejon
  • 439
  • 4
  • 16
  • That worked. But still I'm getting this error `Cannot assign to property: 'dataModel' is a get-only property`. Do you know how can I fixed? – user2924482 Mar 29 '22 at 23:03
  • @user2924482 it looks like you want to have access to your class DataModel. You can gain access with `@StateObject var data = DataModel()`. You don't need to init() the dataModel. – Yotzin Castrejon Mar 29 '22 at 23:22
  • That doesn't work because I need to pass the `NSManagedObjectContext ` .`init(viewContext: NSManagedObjectContext) {` – user2924482 Mar 29 '22 at 23:41
0

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)
        }
malhal
  • 26,330
  • 7
  • 115
  • 133