2011-01-28 190 views
3

假如你有看起来像一个数据模型:核心数据关系

/-----------------------\   /-----------------------\ 
| Patient    |   | Medication   | 
|-----------------------|   |-----------------------| 
| firstName    |   | startOn    | 
| lastName    |   | endOn     | 
|-----------------------|   |-----------------------| 
| medications   | <<-\  |      | 
|      |  \->> | patients    | 
\-----------------------/   \-----------------------/ 

所以有一个多一对多的关系:患者有许多药物和药物有很多病人。

鉴于Patient对象,您如何获得最新的endOn相关的Medication? (假设:一个病人没有超过一种药物在同一日在结束)即:

// patientZero is a patient with related medication records 
Patient *patientZero = ...; 
Medication *mostRecentMed = [patientZero mostRecentlyCompletedMedication]; 

一个怎样实现mostRecentlyCompletedMedication方法?

谢谢!

+0

希望患者不要有许多药物和药物没有多少病人。 ^^ – 2011-01-28 21:57:13

回答

3

这实际上不是一个核心数据问题,而是一个Cocoa集合问题。我会对medications关联集进行排序。假设病人=>用药一对多关联被称为medications

Patient *myPatient; 

NSSet *medications = [myPatient medications]; 
Medication *mostRecent = [medications sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"endOn" ascending:YES]]] 
          lastObject 
          ]; 
+0

圣曼德罗!感谢gosh我为那个电影院展示了!虽然感谢,但很重要的是,它清除了很多东西。不能相信我以前没有看到这个。 – 2011-01-28 21:31:27