您正在从 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