1

Trying to implement core data in SwiftUI, I've run into a wall. Following many tutorials, I wrote the following project, presumably exactly as instructed but the app won't build.

I'm stuck at a very early stage, so I'm hoping someone can help here.

  • I created 2 entities in my XCDtatamodel, each with a string property called "airportName"
  • I simply try to display a list of one of the entities :
import SwiftUI
import CoreData

struct ContentView: View {

    @Environment(\.managedObjectContext) var managedObjectContext

    @FetchRequest(entity: Takeoffs.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Takeoffs.eventDate, ascending: false)]) var fetchedTakeoffs: FetchedResults<Takeoffs>

    var body: some View {

        List {
            ForEach (fetchedTakeoffs, id: \.self) { item in
                Text(item.airportName) // THIS IS WHERE I GET THE ERROR

            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        return ContentView().environment(\.managedObjectContext, context)
    }
}

But Xcode tells me that "Value of type 'NSManagedObject' has no member 'airportName'" It's like my XCDatamodel is not connected to the app.

I created the project by checking the SwiftUI, Use CoreData checkboxes.

The whole code can be found here :

https://github.com/Esowes/RecentExp

Thanks for any pointers.

1 Answer 1

1

I am able to build it. But not sure it would run as you expected it to. Please go through. I think properties of the takeOff items are optional you were getting error.

List {
    ForEach (fetchedTakeoffs, id: \.self) { item  in
       Text(item.airportName ?? "")
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Joy, the "optional" angle was the correct one. I unselected optional in all my entity's properties, except the identNumber which I declared as a UUID. Will that be a problem ? Aren't UUIDs generated automatically ? I'll probably need them when doing ForEach loops in my Lists...
@Esowes. The idea behind UUID is that it is a long string that is unique, for all practical purposes. Let's say in youtube chances are name could be the same, or author or musical is the same for 2 videos. etc... if you want to identify each object uniquely this can be used. No uuid are not generated by default. Using this is better practice for fetching and storing data.I would really glad if you accept the answer. It could push me. That is only if my answer helped you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.