やあ、
データベース開発の経験は豊富ですが、Core Data でのリンク関係を概念化するのに苦労しています。私が理解しているように、多くの関係は 1 つのファイルに添付された NSSet です。ドキュメントを読んだ後、その一部を理解し、以下のコードの最初のインポートで動作するようになりました。
XMLParser を使用して 2 つの個別のインポートを実行するデータ モデルがあります。最初のインポートは、次のように、同じインポート内の同じ XML ファイルからイベントとカテゴリをロードします。
if (thisTagIsForOneTable) {
// Insert object for the one-entity (Events)
self.eventsObject = [NSEntityDescription insertNewObjectForEntityForName:@"Events" inManagedObjectContext:xmlManagedObjectContext];
return;
}
if (thisTagIsForManyTable) {
// Insert object for many-entity (EventCategories)
self.categoriesObject = [NSEntityDescription insertNewObjectForEntityForName:@"EventCategories" inManagedObjectContext:xmlManagedObjectContext];
return;
}
......
// Set attribute values depending upon whether the tag is for the one-entity or the many-entity.
[self.xxxObject setValue:trimmedString forKey:attributeName];
......
// Set the relationship. This works great!
if (thisTagIsForManyTable) {
NSMutableSet *manyRecordSet = [self.eventsObject mutableSetValueForKey:@"categories"]; // My relationship name.
[manyRecordSet addObject:self.categoriesObject];
}
// Save the context. Voila.
上記は正常に動作します。2 番目のインポートでは、アプリケーションの別の部分で EventLocations が個別に読み込まれるため、イベントとの対 1 関係を設定する必要があります。ここがよくわからないところです。ステップはどうあるべきですか?
// Step A) Create (insert) new EventLocations object.
self.eventLocationsObject = [NSEntityDescription insertNewObjectForEntityForName:@"EventLocations" inManagedObjectContext:xmlManagedObjectContext];
// Step B) Locate and get a reference to the the related one-entity's object (Events) by ID? I have a custom class for Events.
// This seems to work but I'm taking a performance hit and getting a compiler warning below. The method returnObjectForEntity does a query and returns an NSManagedObject. Is this correct?
Events *event = (Events *)[self returnObjectForEntity:@"Events" withID:[oneRecordObject valueForKey:@"infIDCode"]];
// Step C) Set the relationship to the Events entity.
if (event) {
[event addLocationsObject:self.eventLocationsObject];
// Compiler warning: incompatible Objective-C types 'struct NSManagedObject *', expected 'struct EventLocations *' when passing argument 1 of 'addLocationsObject:' from distinct Objective-C type
}
// Save the context.
手順 B と C についてはよくわかりません。助けていただければ幸いです。ありがとう。