Skip to content

Instantly share code, notes, and snippets.

@lolgear
Created March 17, 2017 16:26
Show Gist options
  • Save lolgear/54cbbc7a5252c6c20df09ac5759550a0 to your computer and use it in GitHub Desktop.
Save lolgear/54cbbc7a5252c6c20df09ac5759550a0 to your computer and use it in GitHub Desktop.
Core data database cleanup
/*
For example, you use Core Data sqlite.
It is necessary, because sqlite database stores data in single file.
Whole database is single file.
Now you have two options.
1. Delete all data from all tables
2. Delete database sqlite file
Second option is clean but complex.
You should assure every piece of app that database sqlite file doesn't exists.
*/
+ (NSArray *)databaseFilenamesArray:(NSArray *<NSPersistentStore *>)stores {
return [stores valueForKey:@"URL"];
}
+ (NSArray *)databaseEntitiesClassesForModel:(NSManagedObjectModel *)model {
NSArray *result = @[];
for (NSEntityDescription *description in model.entities) {
Class managedObjectClass = NSClassFromString([description managedObjectClassName]);
BOOL isManagedObject = [managedObjectClass isSubclassOfClass:[NSManagedObject class]];
if (isManagedObject) {
result = [result arrayByAddingObject:managedObjectClass];
}
}
return result;
}
+ (void)resetDatabaseModel:(NSManagedObjectModel *)model inContext:(NSManagedObjectContext *)context {
[[self databaseEntitiesClassesForModel:model] enumerateObjectsUsingBlock:^(Class obj, NSUInteger idx, BOOL *stop) {
// truncate all or delete all in iOS 9.
[obj performSelector:@selector(MR_truncateAllInContext:) withObject:localContext];
}];
}
+ (void)removeDatabaseFilesForStores:(NSArray *<NSPersistentStore *>)stores {
for (NSURL *url in [self databaseFilenamesArray:stores]) {
if ([[NSFileManager defaultManager] fileExistsAtPath:url.path]) {
result = result && [[NSFileManager defaultManager] removeItemAtURL:url error:&error];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment