2011-01-28 193 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