0

In core data, I have 10 entities as following :

 + User
    - x
    - xx
 + Store
    - a
    - aa
 + Point
    - n
    - nn
 + ....

And how i can delete all item in User, Store, Point and .... in core data

user7778093
  • 63
  • 1
  • 1
  • 7
  • A quite similar question: [core-data-quickest-way-to-delete-all-instances-of-an-entity](http://stackoverflow.com/questions/1383598/core-data-quickest-way-to-delete-all-instances-of-an-entity). –  May 09 '17 at 08:27
  • Thank you very much – user7778093 May 13 '17 at 10:34

2 Answers2

0

You can get all the entities types in the context (in your case User, Store, Point, etc) from context.persistentStoreCoordinator.managedObjectModel.entities Next, for each entity, you can either make a fetch request to fetch all the enities and then delete each one. This will also update all FetchedResultsController that are monitoring the context. If you don't need that the faster way to do that is to use a NSBatchDeleteRequest for each entity. Don't forget to save the changes to the context at the end.

Jon Rose
  • 8,373
  • 1
  • 30
  • 36
0

If you delete the PersistentStoreCoordinator or Managedobjectmodel then there are chances that there would be persistentStoreCoordinator clashes and exceptions.

So what i did is deleted all the entities and objects from the coredata without forming a new PersistentStoreCoordinator.

- (void)deleteDatabase{
    NSArray *entities = self.managedObjectModel.entities;
    for (NSEntityDescription *entityDescription in entities) {
        [self deleteAllObjectsWithEntityName:entityDescription.name inContext:[APPDELEGATE managedObjectContext]]; // Passing the entity name and context. 
    }
}

- (void)deleteAllObjectsWithEntityName:(NSString *)entityName inContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *fetchRequest =
    [NSFetchRequest fetchRequestWithEntityName:entityName];
    fetchRequest.includesPropertyValues = NO;
    fetchRequest.includesSubentities = NO;

    NSError *error;
    NSArray *items = [context executeFetchRequest:fetchRequest error:&error];

    for (NSManagedObject *managedObject in items) {
        [context deleteObject:managedObject];
    }
}

Use [self deleteDatabase]; for calling the method.