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

标签 objective-c core-data foreign-keys indexing xcdatamodel

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

我如何管理不完全是一对多或一对一或多对多但在核心数据模型中是外键的关系?

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

我如何表示外键关系?索引?

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

最佳答案

您将 CoreData 视为 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;

设置这些很简单:

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

关于objective-c - 如何在核心数据中表示外键关系 - XCode 中的数据模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8603224/

相关文章:

ios - iOS 应用程序中不同用户的核心数据

ios - 如何在不使用 AudioSessionSetProperty 的情况下将音频路由到扬声器?

ios - 不同实体核心数据属性的最大值

sql-server - 忽略索引上的重复值可防止 FOREIGN KEY 约束

ios - 将 iPhone 应用程序连接到接入点

iphone - 核心数据`deleteObject:`问题!

objective-c - 如何使用 NSManagedObjectSubClass 从 CoreData Base 获取所有记录?

mysql - 使用外键时无法在 MySQL [错误 150] 中创建表

mysql - 如何根据父级进行外键更新

ios - 谷歌地图 ios sdk 中心的固定标记