2

I have a Project object that has a to-many relationship to Image, the delete rules are set up as Cascade for project.images and Nullify for image.project. In this case I need to clear out the attached images but leave the project itself intact. There are a lot of images so I want to use a batched delete to get them all in one go.

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Image"];
request.predicate = [NSPredicate predicateWithFormat:@"project = %@", project];
NSBatchDeleteRequest *delete = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];
delete.resultType = NSBatchDeleteResultTypeObjectIDs;
NSError *error;
NSBatchDeleteResult *result = [context.persistentStoreCoordinator executeRequest:delete withContext:context error:&error];
if (error) {
    // todo
}
[NSManagedObjectContext mergeChangesFromRemoteContextSave:@{NSDeletedObjectsKey : [result result]} intoContexts:@[context]];

NSLog(@"images: %@", project.images); // Still has all the images (they are now flagged as isDeleted)

[context save:&error];

NSLog(@"images: %@", project.images); // Still has all the images...

According to the docs the mergeChangesFromRemoteContextSave line should take care of updating the context but this doesn't seem to happen.

One more thing, I know I can set project.images = nil and this does the job, but can't be used in a case when I am only deleting a subset of the images.

Edit: I have investigated further and have more info.

The issue occurs when project.images are faults. If I force them all to fault in then the relationships will successfully updated when the delete goes through. If I leave them as faults then the relationship is untouched and will now point to non-existent objects.

trapper
  • 11,716
  • 7
  • 38
  • 82

1 Answers1

0

In mergeChangesFromRemoteContextSave try including the NSUpdatedObjectsKey with the project's objectID.

[NSManagedObjectContext mergeChangesFromRemoteContextSave:@{NSUpdatedObjectsKey : @[project.objectID], NSDeletedObjectsKey : [result result]} intoContexts:@[context]];`
malhal
  • 26,330
  • 7
  • 115
  • 133