Search code examples
swiftuicore-data

Accessing StateObject's object without being installed on a View. This will create a new instance each time


I am new to SwiftUI and Core Data. I build a View which works fine. In this View I can list my teams and when I add a Team, it is showing in the list. But I get the following Error: Accessing StateObject's object without being installed on a View. This will create a new instance each time.

I found many posts here and I tried to solve this problem, but everytime I solved this I get another error or the added team didn't appear in the list. Does exist a simple solution for this problem in my view?

Here the code of the View:

import SwiftUI
import CoreData

struct View_Teams: View {
    @Environment(\.managedObjectContext) var viewContext
    @FetchRequest(sortDescriptors: []) var teamsListe: FetchedResults<Team>
    
    init() {
        print("teamsListe has got \(teamsListe.count) teams")
    }
    
    var body: some View {

        List {
            ForEach(teamsListe) { team in
                NavigationLink(destination: View_TeamsDetail(passedTeam: team)) {
                    Text(team.bezeichnung ?? "Error")
                }
            }.onDelete(perform: deleteTeam)
        }.navigationTitle("Teams")
        NavigationLink(destination: View_TeamsDetail(passedTeam: nil)) {
            Text("add team")
        }

    }
    
    private func deleteTeam(offsets: IndexSet) {
        withAnimation {
            offsets.map { teamsListe[$0] }
                .forEach(DataController.shared.context.delete)
            DataController.shared.save()
        }
    }
 }

Solution

  • Move the print from init() to body:

    var body: some View {
        let _ = print("teamsListe has got \(teamsListe.count) teams")
    

    The property wrappers aren't ready until body is called and @FetchRequest uses a @StateObject internally.