I am trying, to reset my app which uses Core Data, for this, I have written the code below
- (void) resetApplicationModel
{
// NSError *error;
NSError *error;
// retrieve the store URL
NSURL * storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"abc.sqlite"];
// lock the current context
[self.managedObjectContext lock];
[self.managedObjectContext reset];//to drop pending changes
//delete the store from the current managedObjectContext
if ([[self.managedObjectContext persistentStoreCoordinator] removePersistentStore:[[[self.managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:&error])
{
// remove the file containing the data
if([[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error])
{
//recreate the store like in the appDelegate method
if([[self.managedObjectContext persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error] == nil)
{
NSLog( @"could not create new persistent store at %@ - %@", [storeURL absoluteString], [error localizedDescription]);
}
}
else
{
NSLog( @"could not remove the store URL at %@ - %@", [storeURL absoluteString], [error localizedDescription]);
}
}
else
{
NSLog( @"could not remove persistent store - %@", [error localizedDescription]);
}
[self.managedObjectContext unlock];
__managedObjectContext = nil;
[self managedObjectContext];
_rootViewController.controller = nil;//Make NSFetchResultsController nil;
}
This code works fine on ios 6.1 simulator and there are no issues, but when I check this on iphone 4 running iOS 6.1.3, the persistence file is not deleted and I get error saying
"could not remove the store URL at file://localhost/var/mobile/Applications/147E198E-FAB9-46EA-BE4B-4411AFA013FB/Documents/abc.sqlite - The operation couldn’t be completed. (Cocoa error 4.)"
But all the data is deleted, Now when I try to add new Data inside coreData , I get a error saying
" Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'"
Please help me guys
Regards Ranjit
Create a category on NSManagedObjectContext then implement:
Then to use this simply do:
Pass your entity name in and it will delete it all :-)