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
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
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.
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.