2
votes

Beginner in Core Data here, there is something very basic in Core Data that I don't understand. I know the delete rules, such that if my object gets deleted, if it has relationships that are cascade for example, those relationships will get deleted as well. But what happens on updates?

Example: Person has a relationship to a car. Delete rule is cascade. Person --> Car If Person is deleted, Car will be gone too. But now what if Person just points to another Car, the previous Car will NOT be deleted and will just be dangling in the DB. Any solutions to this?

I figured ideally you should delete the first car before setting the new one, but this is automatically done from a server fetch.

1
What I do in similar situations is to fetch abandoned objects after the update, and delete each one. Cascade deletes are to make your job easier, when they apply, but as you discovered, they trigger only on deletes.Avi

1 Answers

0
votes

If this is the behavior you want in all cases you could override the managed object subclass method to set the new relationship. In the method, check first if another object exists and delete it if desired.

E.g.

-(void) setCar:(Car *)car {
   if (Car* oldCar = self.car) {
        [self.managedObjectContext deleteObject:oldCar];
   }
   [self willChangeValueForKey:@"car"];
   [self setPrimitiveValue:car forKey:@"car"];
   [self didChangeValueForKey:@"car"];
}