如何使用核心数据关系?

时间:2013-03-09 08:38:03

标签: objective-c core-data

我有两个实体:

Patient
- firstName
- lastName
- scheduledAppointments <---->> Appointment

Appointment
- date
- times
- scheduledPatient <<----> Patient

基本上我有一位患者有很多约会。如何在约会实体中设置scheduledPatient?到目前为止我试过这个:

[self.appointment setScheduledPatient:[self.patientArray objectAtIndex:indexPath.row]];

self.appointment.scheduledPatient = [self.patientArray objectAtIndex:indexPath.row];

他们在我编辑约会时工作。但是当我添加一个新的约会时,它会返回一个SIGBRT。

1 个答案:

答案 0 :(得分:0)

您的代码似乎是正确的。 因此,我认为您很可能没有在.xcdatamodel文件中正确定义反向关系。

根据我的理解,你有一对多的关系。也就是说,一名患者可能有许多约会。因此,预约属于一名患者。为了使这种关系在语义上正确,你需要让它知道它们之间的关系。为此,您需要指定关系中每个元素的反向元素。 在下图中,您可以看到一个Region如何拥有多个状态,一个状态属于一个区域。注意连接关系元素的箭头,“many”如何有一个双箭头,“one”有一个箭头。 enter image description here

我相信您很可能忘记在xcdatamodel文件中指定它。

请查看此链接以获取更多信息:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdRelationships.html

Inverse Relationships
Most relationships are inherently bi-directional. If a Department has a to-many relationship to the Employees that work in a Department, there is an inverse relationship from an Employee to the Department. The major exception is a fetched property, which represents a weak one-way relationship—there is no relationship from the destination to the source (see “Fetched Properties”).

You should typically model relationships in both directions, and specify the inverse relationships appropriately. Core Data uses this information to ensure the consistency of the object graph if a change is made (see “Manipulating Relationships and Object Graph Integrity”). For a discussion of some of the reasons why you might not want to model a relationship in both directions, and some of the problems that might arise if you don’t, see “Unidirectional Relationships.”