Search code examples
ioscore-datansmanagedobjectcontext

core data do all relation objects get deleted too when deleting an entity's objects


In core data do all relation objects get deleted too when deleting an entity's objects there is an another entity Details which has one to many relationship. Do I need to delete its objects or the following code takes care of it? my code so far:

 NSFetchRequest * allClients = [[NSFetchRequest alloc] init];
[allClients setEntity:[NSEntityDescription entityForName:@"Client" inManagedObjectContext:[NSManagedObjectContext defaultContext]]];
[allClients setIncludesPropertyValues:NO]; //only fetch the managedObjectID

NSError * error = nil;
NSArray * clients = [[NSManagedObjectContext defaultContext] executeFetchRequest:allClients error:&error];
//error handling goes here
for (NSManagedObject * client in clients) {
    [[NSManagedObjectContext defaultContext] deleteObject:client];
}

NSError *saveError = nil;
[[NSManagedObjectContext defaultContext] save:&saveError];
//more error handling here

Solution

  • That depends on what settings you have configured. For each relationship you can set it to:

    1. Do nothing
    2. Cascade (delete the other item too)
    3. Nullify
    4. Deny (don't allow the deletion)

    You specify this for each relationship in the model (and both ends of each relationship).