添加<key> Object vs insertNewObjectForEntityForName核心数据关系</key>

时间:2010-09-08 21:41:31

标签: core-data import entity-relationship one-to-many key-value-coding

alt text

您好,

虽然我在数据库开发方面有很多经验,但我很难概念化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不太确定。任何帮助都将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

步骤B:请告诉我们编译器警告。 为了加快速度,你可以在开始导入之前创建一个包含所有事件的缓存(NSDictionary)和它们的@“infIDCode”作为Keys。只要您确保在导入阶段没有添加/删除/更改事件,这样可以加快速度。

步骤C: self.eventLocationsObject可能应该声明为EventLocations *。

通常,您的导入应该以这种方式工作