'onAppear is causing problem with the preview but no error is shown

self learning beginner here.

When I remove .onAppear{add()}, the preview works fine. I tried to attach it to other the body view, the Vstack but it causes another error. I read/watched several tutorials but nothing like this is mentioned....

Any help is appreciated

struct ListView: View {

@Environment(\.managedObjectContext) var moc
@FetchRequest(sortDescriptors: []) var targets: FetchedResults<TargetEntity>
@FetchRequest(sortDescriptors: []) var positives: FetchedResults<PositiveEntity>

var body: some View {
    
    VStack {
        Text("+")
        .onAppear{add()} 
        .onTapGesture (count: 2){
            do {
                increment(targets.first!) //I also sense that doing "!" is not good.  But it's the only way I can keep it from causing error "Cannot convert value of type 'FetchedResults' to expected argument type 'X'"
                try moc.save()
            } catch {
                print("error")
            }
        }
    }
}
    
func increment(_ item: TargetEntity) {
        item.countnum += 1
        save()
}

func add() {
    let countnum = TargetEntity(context: moc)
    countnum.countnum = 0
    save()
}

func save() {
    do { try moc.save() } catch { print(error) }
}

}

enter image description here

EDIT 20220509: As advised by @Yrb (great thanks), the error is likely caused by the lack of a proper set up of preview var in the persistence file. I post the relevant code here for visiblity.

Data Controller file

import CoreData
import Foundation

class DataController: ObservableObject {
    let container = NSPersistentContainer(name: "CounterLateApr")
    
    init () {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("Core Data failed to load: \(error.localizedDescription)")
            }
        }
    }
}

preview code in a view

struct ListView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView{
            ListView()
        }        
    }
}

[AppName].app file

import SwiftUI

@main
struct CounterLateAprApp: App {
    
    @StateObject private var dataController = DataController()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, dataController.container.viewContext)
        }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source