创建新的Object1并创建新的Object2(如果存在),然后创建关系

时间:2014-07-18 17:17:50

标签: core-data if-statement save relationship nsmanagedobject

在我的数据模型中,我有:

Object2<-->>Object1

每次按下按钮我都会创建新的Object1,但我的代码当前也在每次保存时创建Object2。我正在尝试创建一个检查,如果Object2存在然后不创建它,但如果它不存在然后创建它。在检查之后,我然后尝试在Object2(创建或现有)和Object1之间创建关系并保存它。我的IBAction中有以下内容:

    - (IBAction)save:(id)sender {

    //create Object1
        Object1 *newObject1 = [NSEntityDescription insertNewObjectForEntityForName:@"Object1"
                                                                    inManagedObjectContext:self.managedObjectContext];

        [newObject1 setValue:self.UILabel.text forKey:@"object1Name"];

    //check if Object2 exists and if it doesn't create new object
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription
                                       entityForName:@"Object2" inManagedObjectContext:self.managedObjectContext];
        [fetchRequest setEntity:entity];

         Object2 *newObject2;
        if (newObject2 == nil)
        {
            newObject2 = [NSEntityDescription insertNewObjectForEntityForName:@"Object2"
                                                                        inManagedObjectContext:self.managedObjectContext];

            [newObject2 setValue:self.UILabel2.text forKey:@"object2Name"];
            newObject2.object2Name = self.UILabel2.text;
        }

 //create relationship from Object1 to Object2        
        newObject1.toObject2 = newObject2;   

        NSError *anyError = nil;
        BOOL savedSuccessfully = [self.managedObjectContext save:&anyError];
        if (!savedSuccessfully) {

        }

    }

目前,每次保存都会继续创建Object2。我如何防止重复Object2?

1 个答案:

答案 0 :(得分:0)

您正在创建获取请求,这是正确的(虽然它可能需要谓词),但您永远不会执行它。执行fetch将返回一个您需要检查的数组(以查看它是否包含任何内容)并从那里提取任何现有对象。

NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:fillInErrorHere...];

if (items.count == 1) {
    newObject2 = items[0];
}