将 NSManagedObject 与 SwiftUI 列表一起使用
Using NSManagedObject with SwiftUI List
我想显示存储为 NSManagedObjects 的 CoreData 记录列表。
我想做这样的事情:
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)
}
}
}
我遇到错误
Initializer 'init(_:rowContent:)' requires that 'Record' conform to 'Identifiable'
我错过了什么?
由于 NSManagedObject
是引用类型,您可以简单地使用 self
作为 id,如下所示
List(records, id: \.self) {record in
RecordRow(record: record)
我想显示存储为 NSManagedObjects 的 CoreData 记录列表。
我想做这样的事情:
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)
}
}
}
我遇到错误
Initializer 'init(_:rowContent:)' requires that 'Record' conform to 'Identifiable'
我错过了什么?
由于 NSManagedObject
是引用类型,您可以简单地使用 self
作为 id,如下所示
List(records, id: \.self) {record in
RecordRow(record: record)