3
votes

I am trying to figure out the best way to bulk delete objects inside of my Core Data database.

I have some objects with a parent/child relationship. At times I need to "refresh" the parent object by clearing out all of the existing children objects and adding new ones to Core Data. The 'delete all' portion of this operation is where I am running into trouble. I accomplish this by looping through the children and calling deleteObject for each one.

I have noticed that after the NSManagedObjectContext:Save call following all of the deleteObject calls is very slow when I am deleting 15,000 objects.

How can I speed up this call? Are there things happening during the save operation that I can be aware of and avoid by setting parameters different or setting up my model another way? I've noticed that memory spikes during this operation as well. I really just want to "delete * from".

Thanks.

3

3 Answers

1
votes

Supposing that you have in your Core Data model a parent and a child entities, and the parent has a to-many relationship to child called children, you should be able to delete all of the child objects without looping as follows:

NSManagedObject *parentObject = ...;
[parentObject setValue:nil forKey:@"children"];

or using the Core Data generated method

- (void)removeChildren:(NSSet *)value;

NSSet *children = [parentObject valueForKey:@"children"];
[parentObject removeChildren:children];

I am not sure if this will speed up the NSManagedObjectContext save operation. Please let me know about the performances.

1
votes

Check the relationship dependency graph: a cascade of deletes triggered by the initial deletion will slow things down. If those deletes are unnecessary then change the deletion rule.

1
votes

according to apple website : http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdCreateMOs.html it is very simple :

Deleting a managed object is straightforward. You simply send its managed object context a deleteObject: message, passing the object you want to delete as the argument.

[aContext deleteObject:aManagedObject];

This removes the managed object from the object graph. Just as a new object is not saved to the store until the context is saved, a deleted object is not removed from the store until the context is saved.