SwiftData - Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSFetchRequest could not locate an NSEntityDescription for entity name 'Workout

This piece of code was working properly until I Introduced the Exercise Model. I have tried everything like using migration scheme, removing the app, cleaning build folder, trying on different devices and simulator. Nothing seems to work now. I can't get the app to launch.

struct LogbookApp: App {
    
    @State private var sharedModelContainer: ModelContainer = {
        let schema = Schema([
            Workout.self,
            Exercise.self
        ])
        
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch(let error) {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()
    
    var body: some Scene {
        
        WindowGroup {
            
            MainCoordinator()
                            .view()
        }
        .modelContainer(sharedModelContainer)
    }
}

The models look like this

@Model
final class Exercise {
    
    var name: String
    var workout: Workout?
    
    init(name: String, workout: Workout? = nil) {
        self.name = name
        self.workout = workout
    }
}

@Model
final class Workout {
    
    @Attribute(.unique) var id = UUID()
    @Relationship(deleteRule: .cascade) var exercises: [Exercise]?
    
    var type: WorkoutType
    var date: Date
    var duration: Int
    var customDescription: String
    
    init(id: UUID = UUID(),
         type: WorkoutType,
         date: Date,
         duration: Int,
         customDescription: String = "",
         exercises: [Exercise]? = []) {
        
        self.id = id
        self.type = type
        self.date = date
        self.duration = duration
        self.customDescription = customDescription
        self.exercises = exercises
    }
}
  • *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSFetchRequest could not locate an NSEntityDescription for entity name 'Workout'' *** First throw call stack: Accessing Environment<ModelContext>'s value outside of being installed on a View. This will always read the default value and will not update.

    libc++abi: terminating due to uncaught exception of type NSException

Add a Comment

Replies

If you are trying to access the data outside a view you need to send the modelContext as a parameter.

@Environment(\.modelContext) var modelContext 

functionToPerformActionInAStructOutideYourView(modelContext)

Then in your struct

func functionToPerformActionInAStructOutideYourView(_ modelContext: ModelContext){

let possiblyAFetchRequest = FetchDescriptor<Workout>(predicate: #Predicate{ ...})

do {
try modelContext.fetch(possiblyAFetchRequest)
}
catch {}

}