如何在核心数据中表示外键关系 - XCode中的数据模型

cal*_*rio 5 indexing core-data foreign-keys objective-c xcdatamodel

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

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

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

我怎样才能代表外键关系呢?指标?

非常感谢,希望我的问题很明确.

MGA*_*MGA 8

您正在考虑使用DBMS而不是DBMS.您无需设置外键即可在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;
Run Code Online (Sandbox Code Playgroud)

设置这些就像这样简单:

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.
Run Code Online (Sandbox Code Playgroud)

希望这有助于清理一些事情!阅读文档以确保CoreData适合您!

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