5

Core Data 是全新的,我正在制作我的数据模型。我有 33 个实体,它们之间的硬关系很少,但有很多外键关系。

如何管理不完全是 1-many 或 1-1 或 many-many 但在 Core Data Model 中是外键的关系?

例如,我有一个 Contact 实体,它与contact_x_mail 有关系,同时contact_x_mail 与包含所有电子邮件的Mail 有关系。这种关系是一对多或多对多。但是还有其他的,比如机构(一个联系人可以有很多机构)和邮件,这不是一对多或一对一的关系,机构有一个 ForeignKey_mail_id。

我怎样才能表示外键关系?索引?

非常感谢,希望我的问题很清楚。

4

1 回答 1

8

您正在从 DBMS 的角度考虑 CoreData,但事实并非如此。您无需设置外键即可在 CoreData 中建立关系。如果您想将电子邮件分配给用户,您只需在两者之间创建关系,您可以设置用户的属性“电子邮件”或电子邮件的“用户”属性。foreignKey 和链接都是由 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:@"matt@stackoverflow.com"];

//...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

于 2011-12-28T05:59:29.710 回答