iOS核心数据如何正确初始化实体关系? [英] iOS Core Data how to properly initialize entity relationships?

查看:153
本文介绍了iOS核心数据如何正确初始化实体关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a one to many relationship in my core data model. I need to create a new entity and save it. The entity has a one to many relationship which generated the following code:

- (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];

//保持添加单个动态属性

//keep adding individual dynamic properties

将-toMany关系集最初设置为nil是正确的吗?或者我需要初始化一个(空吗?)在这里设置并分配吗?

is it correct to set the -toMany relationship sets to nil initially? Or do I need to initialize an (empty?) set here and assign it? Would I be able to add extra objects later if I set the initial set to 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();

        }


推荐答案

您不需要初步了解您的关系。只需使用提供的访问器或辅助函数,Core Data即可处理。 IOW,只在您需要实际使用它时才担心属性/关系。

You don't need to intialize your relationships. Just use the supplied accessors or helper functions and Core Data takes care of it. IOW, only worry about the property/relationship when you need to actually use it.

Andrew

这篇关于iOS核心数据如何正确初始化实体关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆