0

There is a core data model with two entities i my iOS application.

Entity: Unit / Attributes: unit_name - NSString

->> Relationship to Exercise (one to many)

Entity: Exercise / Attributes: exercise_name - NSString .

So one unit can have many exercises.

In my table view controller are all available exercises listed. (So in the first time, i make a fetch request for the Exercise entity and the managedObjectContext points to this entity.

If i want to save a "NEW" unit with exercises the save function doesn't work. There is no error at all, but the unit table is still empty.

Here is the code for the save function:

 Units *newUnit = [NSEntityDescription insertNewObjectForEntityForName:@"Units"   inManagedObjectContext:[self.coreDataHelper managedObjectContext]];
    newUnit.unit_name = unitTextField.text;//Attribute
    newUnit.exercises = exerciseSet;//Relationship (NSSet)

    NSError *error = nil;
    if (![[self.coreDataHelper managedObjectContext]save:&error]) {
        NSLog(@"There was an error! %@", error);
    }
    else {
        NSLog(@"Success!");
    }

It seems like the managedObjectContext still points to the Exercise entity. (Because it was initialized the first time with this entity) the coreDataHelper has the NSPersistentStoreCoordinator, the NSManagedObjectContext, the NSManagedObjectModel and some methods to read write and delete.

Thanks for help!

Sachin
  • 40,216
  • 7
  • 90
  • 102
Steffen Ruppel
  • 331
  • 2
  • 11
  • 2
    Does you question have a typo, or does your code have "Units" in the insertNewObjectForEntityName method, while you said that your entity is Unit? – rdelmar Mar 20 '13 at 22:40
  • 2
    Any entity will be saved that contains the context. Make sure the self.coreDataHelper is not null and that you are passing this to the current controller properly. – Mark McCorkle Mar 20 '13 at 22:49

1 Answers1

0

Just to verify that everything is connected the way it ought to be, add

NSAssert(self.coreDataHelper, @"null coreDataHelper");
NSAssert(self.coreDataHelper.managedObjectContext, @"null MOC");
NSLog(@"available entities: %@", 
    self.coreDataHelper.managedObjectContext.persistentStoreCoordinator.managedObjectModel.entitiesByName);

You ought to see "Units" as one of your entities, if you've set everything up correctly.

And then after your insertion of newUnit, verify that it worked: NSAssert(newUnit, @"newUnit didn't get inserted");

This smells like a logic error to me, by the way: you're creating a new Units instance every time you save? Are you sure you don't want to use a find-or-create pattern instead?

Hal Mueller
  • 7,019
  • 2
  • 24
  • 42