ioscore-datansfetchrequestnsentitydescription

iOS: core data update object with one- with to-many relationship


In my app I have this code to update a DB:

NSManagedObjectContext *context = [self managedObjectContext];

NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Struct"];
        NSError *error = nil;

        for (id element in array){
            [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"id==%@",[element objectForKey:@"id"]]];

            Struct *struct = [[context executeFetchRequest:fetchRequest error:&error] lastObject];

            if (struct != nil){
                //updating value of attributes
                struct.name = [element objectForKey:@"n"];
                struct.val = [element objectForKey:@"val"];
                struct.pos = [element objectForKey:@"pos"];


            }
             else{
              //create a new identity
             }
         }

it's all ok but I have other two objects in relationship with Struct:

"Id_Loc" (one to many) "Details" (one to one)

I don't know how to update them, I don't know how to call them from my object 'Struct' I don't find nothing Can you help me? thanks


Solution

  • It works the same way you're using .name, .val and .pos.

    The one-to-one relationship will return an object, the one-to-many relationship will return a NSSet.

    Say your one-to-one relationship is from Struct to Bar and the relationship name is bar, you'll receive a Bar object by using struct.bar.

    Edit: If you want to add new objects to the one-to-many relationship you should use [struct addFooObject:]; where Foo is your objects name.