你好,
虽然我在数据库开发方面有很多经验,但我很难在 Core Data 中概念化链接关系。据我了解,许多关系是一个附加到一个文件的 NSSet。阅读文档后,我已经理解了其中的一部分,并使其在下面代码的第一次导入中工作。
我有一个数据模型,我使用 XMLParser 在其中执行两个单独的导入。第一次导入从同一个导入中的同一个 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.
以上工作正常。第二个导入在应用程序的不同部分分别加载 EventLocations,因此我需要将其设置为与事件的一对一关系。这是我不太确定的地方。步骤应该是?
// 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。任何帮助将不胜感激。谢谢。