nOk
nOk

Reputation: 3439

Filling a List in SwiftUI with CoreData

I'm trying to fill a List with all entries from my "FlightRecording" entity. but I can't use Text(recording.name) because it says "NSManagedObject has no member 'name' ". Why is this even a NSManagedObject and not an object of type 'FlightRecordings' ?

struct FlightRecorderBrowser: View {
    let flightRecordings: [FlightRecording] = FlightRecorder().fetchAllRecordings()
    var body: some View {
        NavigationView {
            List() {
                ForEach(flightRecordings, id: \.self) {recording in
                    Text(recording.name)
                }
            }

            .navigationBarTitle("Flight Recordings")
        }
    }
}

Upvotes: 3

Views: 1368

Answers (1)

Fabian
Fabian

Reputation: 5348

Try to add an explicit type to the ForEach closure since a recording can be an NSManagedObject and a FlightRecording at the same time so the compiler just decided to use NSManagedObject.

ForEach(flightRecordings, id: \.self) { (recording: FlightRecording) in
    Text(recording.name)
}

Edit: If recording.name is optional you have to force-unwrap it or provide an alternative for Text to be able to use the value. recording.name! or recording.name ?? "default-text"

Another option to avoid errors on force-unwrap is to only show Text if if recording.name != nil.

Upvotes: 5

Related Questions