Home > database >  SwiftUI: Property type does not match wrappedValue for type FetchedResults<NSManagedObject>
SwiftUI: Property type does not match wrappedValue for type FetchedResults<NSManagedObject>

Time:03-31

I'm trying to implement this solution: 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

CodePudding user response:

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> 

CodePudding user response:

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)
        }
  • Related