Overview:
- I remove an NSManagedObject using the remove methods provided in the autogenerated NSManagedObject subclass
- Then I attempt to save the database
- 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:
- Why is it that the saving the Database not successful after using the remove methods?
- 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.
- 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