0

使用这个问题/答案,我可以使用 ForEach 来使用从 CoreData 中的一对多关系创建的 NSOrderedSet,但是我似乎无法访问存储在 Core Data 实体中的字符串属性。

我有两个 CoreData 实体:Client 和 SessionNote。Clients可以有多个SessionNotes,clientNotes的NSOrderedSet,SessionNote只能有一个Client。

客户端+CoreDataClass.swift:

public class Client: NSManagedObject {

}

客户端+CoreDataProperties.swift:

extension Client {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Client> {
        return NSFetchRequest<Client>(entityName: "Client")
    }

    @NSManaged public var firstName: String?
    @NSManaged public var lastName: String?
    @NSManaged public var id: UUID?
    @NSManaged public var clientNotes: NSOrderedSet?

}

SessionNote+CoreDataClass.swift:

public class SessionNote: NSManagedObject {

}

SessionNote+CoreDataProperties.swift:

extension SessionNote {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<SessionNote> {
        return NSFetchRequest<SessionNote>(entityName: "SessionNote")
    }

    @NSManaged public var date: Date?
    @NSManaged public var noteText: String?
    @NSManaged public var id: UUID?
    @NSManaged public var clientOrigin: Client?

}

这是ClientDetailView.swift:

struct ClientDetailView: View {

    @Environment(\.managedObjectContext) var moc

    @ObservedObject var selectedClient: Client


    var body: some View {
        Form {
            HStack {
                Text("\(selectedClient.firstName ?? "") \(selectedClient.lastName ?? "")")
            }
            Section() {
                ForEach(Array(selectedClient.clientNotes!.set), id: \.self) { note in
                    Text("This will repeat for the number of notes in the clientNotes NSOrderedSet")
                    /*
                     But instead I want to be able to display the noteText
                     string attribute stored in the SessionNote CoreData entity
                     instead of the above placeholder.
                    */
                }
            }

        }

    }
}

我已经尝试过Text("\(note.noteText ?? "")"),但它会引发以下错误:

“AnyHashable”类型的值没有成员“noteText”

当我尝试Text("\(self.selectedClient.clientNotes!.value(forKeyPath: \SessionNote.noteText))")时,它会引发以下错误:

协议类型“任何”不能符合“_FormatSpecifiable”,因为只有具体类型才能符合协议

是否有为每个 SessionNote noteText 实体显示不同的字符串值?

4

1 回答 1

1

您可以使用array方法 onNSOrderedSet并将其强制类型转换为[SessionNote],因为您知道您将始终将SessionNote类存储到有序集。

ForEach(selectedClient.clientNotes!.array as! [SessionNote], id: \.self) { (note: SessionNote) in
    Text(note.text ?? "")
}

由于在您希望使用音符的每个地方都需要进行这种铸造。您还可以在您的内部添加一个计算属性,Client该属性始终为您提供SessionNote数组的类型化版本。

extension Client {
  var typedClientNotes: [SessionNote] {
    return (clientNotes?.array as? [SessionNote]) ?? []
  }
}

而且,通过这些新变化,您可以ForEach做得更好。

ForEach(selectedClient.typedClientNotes, id: \.self) { note in
    Text(note.text ?? "")
}

出于这个原因,我尝试使用正常Set的核心数据关系。因为它可以输入,并且使使用 Coredata 变得非常有趣。但是,NSOrderedSet尽管是一个无类型的集合,但它有自己的优势。

于 2019-11-21T20:59:12.640 回答