2011-12-22 10 views
5

全新的核心數據,我正在製作我的數據模型。我有33個實體,他們之間的關係很少,但有很多外鍵關係。如何在覈心數據中表示外鍵關係 - 在XCode中的數據模型

如何管理不完全是1-many或1-1或many-many的關係,而是Core Data Model中的外鍵?

例如,我有一個Contact實體,它與contact_x_mail有關係,同時contact_x_mail與Mail有關係,包含所有電子郵件。這種關係是1-many或many-many。但也有其他機構(聯繫可以有許多機構)和郵件,這不是一對多或1-1關係,Institution有一個ForeignKey_mail_id。

如何表示外鍵關係?指標?

非常感謝,希望我的問題很明確。

+0

我不確定我是否真的明白。如果一個關係不是1-M,M-M或1-1那麼它是什麼? – paulbailey 2011-12-22 12:59:45

回答

8

你在考慮CoreData,它不是DBMS。您不需要設置外鍵來在CoreData中建立關係。如果要爲用戶分配電子郵件,則只需在兩者之間創建一個關係,並且可以設置用戶的屬性「電子郵件」或電子郵件的「用戶」屬性。外鍵和鏈接全部由CoreData在後臺完成。

另一方面,每個關係的定義如下:1-1,1- *或-。我不確定是否有其他選擇...

當您在CoreData中創建關係時,您正在有效地爲此項目創建新屬性。這裏有一個例子:

@interface User : NSManagedObject 

#pragma mark - Attributes 
@property (nonatomic, strong) NSString *name; 
@property (nonatomic, strong) NSString *emailAddress; 

#pragma mark - Relationships 
//All to-many relationships are saved as Sets. You can add to the "emails" relationship attribute to add email objects 
@property (nonatomic, strong) NSSet  *emails; 
//All to-one relationships are saved as types of NSManagedObject or the subclass; in this case "Institution" 
@property (nonatomic, strong) Institution *institution; 

設置這些很簡單,只要:

User *user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:[self.fetchedResultsController managedObjectContext]]; 
[user setName:@"Matt"]; 
[user setEmailAddress:@"[email protected]"]; 

//...Maybe i need to query my institution 
NSFetchRequest *query = [[NSFetchRequest alloc] initWithEntityName:@"Institution"]; 
    [bcQuery setPredicate:[NSPredicate predicateWithFormat:@"id == %@",  institutionId]]; 
    NSArray *queryResults = [context executeFetchRequest:query error:&error]; 
[user setInstitution:[queryResults objectForId:0]]; 

//Now the user adds a email so i create it like the User one, I add the proper 
//attributes and to set it to the user i can actually set either end of the 
//relationship 
Email *email = ... 
[email setUser:user]; 

//Here i set the user to the email so the email is now in the user's set of emails 
//I could also go the other way and add the email to the set of user instead. 

希望這有助於明確了一點東西!閱讀文檔以確保CoreData適合您!

http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/CoreData.pdf