iphaaw
iphaaw

Reputation: 7204

Using NSManagedObject with SwiftUI List

I want to display a list of CoreData records stored as NSManagedObjects.

I want to do something like this:

struct RecordView: View 
{
    @State var records:[MyRecord] //[NSManagedObject]

    var body: some View 
    {
        VStack
        {
            List(records) {record in // Error: Initializer 'init(_:rowContent:)' requires that 'Record' conform to 'Identifiable'
                RecordRow(record: record)
        }
    }
}

struct RecordRow: View {
    var record: Record //NSManagedObject

var body: some View
{
    NavigationLink(destination: RecordForm(record: record))
    {
        HStack
        {
            Text(record.name)
                .frame(width: 140, height: 50, alignment: .leading)
        }
    }

}

I'm getting an error

Initializer 'init(_:rowContent:)' requires that 'Record' conform to 'Identifiable'

What have I missed?

Upvotes: 2

Views: 432

Answers (1)

Asperi
Asperi

Reputation: 257711

As NSManagedObject is reference type, you can simply use self for each as id like below

List(records, id: \.self) {record in
   RecordRow(record: record)

Upvotes: 2

Related Questions