Fetch core data entity in list

Viewed 643

The core data User I create with property id and name, which I want to fetch it into list.

struct MyView: View {
    @FetchRequest(entity: User.entity(), sortDescriptors: []) var users: FetchedResults<User>

    var body: some View {
        VStack {
            List {
                ForEach(users, id: \.id) { user in  // Type '_' has no member 'id'
                    // Text(user.name)
                }
            }
        }
    }
}

I'm confused with the error report seems it is not successfully import core data entity.

UPDATE

When I try to use the name property in list, it also report Value of type 'NSManagedObject' has no member 'name' error message.

ForEach(users, id: \.id) { user in
    Text(user.name)
}
2 Answers

At times, you need to build the project for the entity to be recognized in code. Here's the code for loading the CoreData entity User with id and name.

struct ContentView: View {
    @Environment(\.managedObjectContext) var context
    @FetchRequest(entity: User.entity(), sortDescriptors: [])
    var users: FetchedResults<User>

    var body: some View {
        List {
            ForEach(users, id: \.id) { user in
                Text("Id = \(user.id), Name = \(user.name ?? "")")
            }
        }
    }
}

Alternatively, you can make the User entity conform to Identifiable. Doing so, you can skip the id parameter in the ForEach.

extension User: Identifiable {
}

ForEach(users) { user in
    Text("Id = \(user.id), Name = \(user.name ?? "")")
}

User entity setup

Referencing this article, I create a new UserRow struct to hold the core data entity, and it works correctly for me. But I think there is some knowledge I have missing in this situation, it will be very kind if someone could explain for me.

// in MyView add the new struct

struct UserRow: View {
    var user: User

    var body: some View {
        Text(user.name ?? "No name given")
    }
}


// then replace the list with

List {
    ForEach(users) { user in
        UserRow(user: user)
    }
}
Related