iOS Core Data如何正确初始化实体关系?

时间:2011-10-27 18:38:17

标签: core-data ios5 entity-relationship nsmanagedobject

我的核心数据模型中有一对多的关系。我需要创建一个新实体并保存它。该实体具有一对多关系,生成以下代码:

- (void)addRelationshipEvent1:(NSSet *)values;
- (void)removeRelationshipEvent1:(NSSet *)values;

        NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
        NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
        ApplicationRecord *newManagedObject = (ApplicationRecord*)[NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];


        newManagedObject.startDate = [NSDate date];
        newManagedObject.stopDate = [[NSDate date] dateByAddingTimeInterval:120];

//继续添加单个动态属性

最初将-toMany关系集设置为nil是否正确?或者我是否需要在此处初始化(空?)并分配它?如果我将初始设置设置为nil,我是否可以稍后添加额外的对象?

        newManagedObject.relationshipEvent1  = nil;
        newManagedObject.relationshipEvent2 = nil;
    //...

        // Save the context.
        NSError *error = nil;
        if (![context save:&error])
        {
            /*
             Replace this implementation with code to handle the error appropriately.

             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();

        }

1 个答案:

答案 0 :(得分:3)

亚历,

您不需要初始化您的人际关系。只需使用提供的访问器或辅助函数,Core Data就可以处理它。 IOW,只需要在实际使用时担心属性/关系。

安德鲁