Search code examples
ioscore-datansmanagedobject

iOS - core data - save unsuccessful after using remove methods in NSManagedObject Subclasses


Overview:

  1. I remove an NSManagedObject using the remove methods provided in the autogenerated NSManagedObject subclass
  2. Then I attempt to save the database
  3. The database save is unsuccessful.

.

 - (void)removeEmployees:(NSSet *)values; //Auto generated method in Department.h

However adding of an NSManagedObject using the add method allows the database to be saved successfully

 - (void)addEmployeesObject:(Employee *)value; //Auto generated method in Department.h - works fine

Note: I am using NSManagedObject subclasses generated by XCode.

Entity Details:

  • I have 2 tables (entities) namely "Employee" and "Department"
  • One department can contain multiple employees
  • One employee can only belong to one department

Relationship Details:

  • Relationship from an "Employee" to "Department" is a One to One relationship and is called "whichDepartment". Delete rule is Nullify
  • Relationship from an "Department" to "Employee" is a Many to One relationship and is called "employees". Delete rule is Cascade

Problem:

"Department" class has a method called as mentioned below, after I use this method, the database save is not successful

(void)removeEmployees:(NSSet *)values; //Auto generated method in Department.h //does not work

Code used to Delete:

- (void) removeEmployeesHavingAgeAsZeroWithDepartment: (Department*) department

{
    NSMutableSet *employeesSetToBeRemoved = [[NSMutableSet alloc] init];

    for(Employees *currentEmployee in department.employees)
    {
        if(currentEmployee.age == 0)
        {
            [employeesSetToBeRemoved addObject:currentEmployee];
        }
    }

    [department removeEmployees:employeesSetToBeRemoved]; //causing the problem
}

Code used to save the database

[self.database saveToURL:self.database.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) 
  {NSLog(@"DB saved");}];

Questions:

  1. Why is it that the saving the Database not successful after using the remove methods?
  2. Do I need to implement this method ? currently i don't see any implementation for this method, I can only find it in the header file.
  3. Are my relationships (inverse, delete rules, etc) set up correctly ?

Answer:

  • Pls refer to Jody's answer and comments (May 17 at 4:39), it is explained well as how to debug the problem and find the root cause

Solution

  • After some investigation, I realized that the database was not getting saved.

    Instead of using the auto generated remove method, I used the NSManagedObjectContext's deleteObject method

    Fix:

    [self.managedObjectContext deleteObject:currentEmployee];