5

Core Data をまったく初めて使用して、データ モデルを作成しています。私は 33 のエンティティを持っており、それらの間の難しい関係はほとんどありませんが、多くの外部キー関係があります。

厳密には 1 対多、1 対 1、または多対多ではなく、Core Data Model の外部キーである関係をどのように管理できますか?

たとえば、contact_x_mail と関係がある Contact エンティティがあり、同時に contact_x_mail はすべてのメールを含む Mail と関係があります。この関係は、1 対多または多対多です。しかし、機関 (連絡先は多くの機関を持つことができます) やメールのようなものもあります。これは 1 対多または 1 対 1 の関係ではありません。機関には ForeignKey_mail_id があります。

その外部キー関係をどのように表現できますか? インデックス?

どうもありがとう、私の質問が明確であることを願っています。

4

1 に答える 1

8

CoreData は、そうではない DBMS の観点から考えています。CoreData でリレーションシップを作成するために外部キーを設定する必要はありません。ユーザーに電子メールを割り当てたい場合は、2 つの関係を作成するだけで、ユーザーの「電子メール」属性または電子メールの「ユーザー」属性を設定できます。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 に答える