When I try to migrate my old db to a new db, it is all done correctly. But when I try to access the db, it says its corrupted or malformed. It happens only in iOS11.
I get this error -
error: exception handling request: <NSSQLRelationshipFaultRequestContext: 0x1c4cbc9e0> , Fatal error. The database at /var/mobile/Containers/Data/Application/743F0953-2F57-4B9F-931A-0E0AEF9E8D0A/Documents/Main.db is corrupted. SQLite error code:11, 'database disk image is malformed' with userInfo of {
NSFilePath = "/var/mobile/Containers/Data/Application/743F0953-2F57-4B9F-931A-0E0AEF9E8D0A/Documents/Main.db";
NSSQLiteErrorDomain = 11;
}
When I try accessing db, I get -
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Object's persistent store is not reachable from this NSManagedObjectContext's coordinator'
This is my code of migration -
NSError *error = nil;
NSMappingModel *mapping = [NSMappingModel inferredMappingModelForSourceModel: oldModel destinationModel: self error: &error];
if (error) {
LOG(#"Error while inferring mapping model: %#", error);
return NO;
}
NSString *newContextPath = [contextPath stringByAppendingPathExtension: #"tmp"];
NSValue *classValue = [[NSPersistentStoreCoordinator registeredStoreTypes] objectForKey: NSSQLiteStoreType];
Class sqliteStoreClass = (Class)[classValue pointerValue];
Class sqliteStoreMigrationManagerClass = [sqliteStoreClass migrationManagerClass];
NSURL *srcURL = [NSURL fileURLWithPath: contextPath], *dstURL = [NSURL fileURLWithPath: newContextPath];
NSMigrationManager *manager = [[sqliteStoreMigrationManagerClass alloc] initWithSourceModel: oldModel destinationModel: self];
#try {
if (![manager migrateStoreFromURL: srcURL type:NSSQLiteStoreType options:nil withMappingModel:mapping toDestinationURL: dstURL destinationType:NSSQLiteStoreType destinationOptions:nil error:&error]) {
LOG(#"Migration failed %#", error);
return NO;
}
} #catch (NSException *exception) {
LOG(#"Exception: %#", exception);
return NO;
}
if (![[NSFileManager defaultManager] removeItemAtPath: contextPath error: &error]) {
LOG(#"Error removing old database: %#", error);
return NO;
}
if (![[NSFileManager defaultManager] moveItemAtPath: newContextPath toPath: contextPath error: &error]) {
LOG(#"Error renaming/moving new database: %#", error);
return NO;
}
LOG(#"- Context Migration: Complete");
I finally found out, I was deleting only .db file but not .shm and .wal files. This was okay with iOS10 and below, but somehow corrupts the db in iOS11. So, deleted both the old .shm and .wal files fixed the issue.
If anyone struggling what is going wrong, this might be of some help.
I am new to Xcode and ios. I am using Xcode 7.3 version and swift2.2
I have removed a per-populated SQlite Db from my project. Later, I used Add file menu in Xcode to add the same name SQLite Db with only modified the content of the field. Example , fieldname :addr , the content :123, 5th ave , now the same filedname :addr ,the content :12, Broadway
After added the modified content SQLite DB, the code STILL using the old content that is 123,5th ave!
let querySQL = "select Sid, location, Addr from tblPlaces where Sid =" + myId
let result: FMResultSet? = MyDB.executeQuery(querySQL, withArgumentsinArray:nil)
if result?.next() == true {
let strAddr = results!stringForColumn("Addr")
}else {
}
I have created a class to handle the creation of SQLite DB in AppDelegate:
Util.copyFile("SqliteDB filename")
here the code:
class func copyFile(fileName: NSString) {
var dbPath: NSString = getPath(fileName)
var fileManager = NSFileManager.defaultManager()
if !fileManager.fileExistsAtPath(dbPath) {
let documentsURL = NSBundle.mainBundle().resourceURL
let fromPath = documentsURL!.URLByAppendingPathComponent(filename as string)
var error : NSError?
do {
try filemanager.CopyItemAtPath(fromPath.path!, toPath: dbPath)
}catch let error1 as NSError {
error = error1
}
}
// GetPath of the SQLite file
class func getPath(filename : String) -> string {
let documentDirectory = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,inDomain:
UserDomainMask, appropriateURLURL:nil, create: true)
return documentDirectory.URLbyAppendingPathComponent(filename).path!
}
What this happened? How to do the right way?
If I remove the SQlite Db file say MyDB.sqlite, and later I add in the same name Db file with content modified, I should get the new content. But this is not the case.
You are putting your file in the application bundle, i.e., to be distributed with your app. That file is read only. To update the file (including scheme restructuring) you would need to copy the the file to your documents folder, and update it there. Otherwise, your update will fail, leaving you with the same file as before.
I think this is what is happening.
For distribution it is also necessary that any such file be flagged NOT to backup to icloud or the app is rejected.
I use the following method (sorry, obj c) to copy the file from the bundle to the documents directory (sorry this code is sloppy but it may convey the basic idea).
+ (void)copyBundleFileToStoresDirectory:(NSString *)filename
{
NSError *error;
NSURL *fileURL = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:filename ofType:nil]];
NSURL *pathURL = [SVOFileSystemMethods documentsSubdirectory:#"Stores" skipBackup:YES];
if (fileURL)
{
if([[NSFileManager defaultManager] copyItemAtURL:fileURL toURL:pathURL error:&error])
{
// NSLog(#"File successfully copied");
}
else
{
[[[UIAlertView alloc]initWithTitle:NSLocalizedString(#"error", nil) message: NSLocalizedString(#"Failed to copy database from bundle.", nil)
delegate:nil cancelButtonTitle:NSLocalizedString(#"OK", nil) otherButtonTitles:nil] show];
NSLog(#"Error description-%# \n", [error localizedDescription]);
NSLog(#"Error reason-%#", [error localizedFailureReason]);
}
}
}
// // flags URL to exclude from backup //
+ (BOOL) addSkipBackupAttributeToItemAtURL:(NSURL *)URL {
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success)
{
NSLog(#"Error excluding %# from backup %#", [URL lastPathComponent], error);
}
return success; }
I have UIDocument in iCloud ubiquitous container and I need to append data to file while saving document. I override readFromURL:: and writeContents::::: method according UIDocument documentation:
-(BOOL) writeContents:(id)contents toURL:(NSURL*)url forSaveOperation:(UIDocumentSaveOperation)saveOperation originalContentsURL:(NSURL*)originalContentsURL error:(NSError *__autoreleasing *)outError
{
NSFileCoordinator* coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:self];
NSError* error = nil;
[coordinator coordinateWritingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
NSData* data = contents; //correct, non-empty NSData
///[data writeToFile:newURL :] works, but overwrite original file
NSOutputStream* stream =[[NSOutputStream alloc] initWithURL:newURL append:YES];
if (stream)
{
NSInteger written = [stream write:data.bytes maxLength:data.length];
if (written != data.length)
{
//failed here, written == -1
NSLog(#"Write data to UIDocument failed: %#, error: %#", newURL, stream.streamError);
}
}
else
{
NSLog(#"Write data to iCloudDocument failed: %#", newURL);
}
}];
if (error)
{
NSLog(#"Coordinated write failed %#, error: %#", url, error);
*outError = error;
}
return error == nil;
}
Accessor block has different newURL, for example:
url: file:///private/var/mobile/Library/Mobile%20Documents/XXXXXXX~com~test~test/test.doc
newURL: file:///private/var/mobile/Applications/5631D484-7661-4E9E-A342-B25297FC0E18/tmp/(A%20Document%20Being%20Saved%20By%20test%20)/test.doc.
[stream write::] failed, because newURL file dosn't exists and I can't append data, only create file with all document's content.
Document editing code:
NSURL* url = [self.containerURL URLByAppendingPathComponent:kCloudDocumentName];
MyDocument* document = [[MyDocument alloc] initWithFileURL:url];
[document openWithCompletionHandler:^(BOOL success) {
if (success)
{
//update some document data
[self updateData:document completion:nil];
[document closeWithCompletionHandler:^(BOOL success) {
//failed here!
}];
}
}];
MyDocument exists in ubiquitous container at url and document has Normal state.
How I can do incremental writing in this case? Whats wrong?
After changing data in your UIDocumnet you can use:
-[UIDocumnet saveToURL:UIDocumnet.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:nil];
Not sure, it's right or not but it works in my app. If it's wrong, correct me please somebody.
You may need to overwrite this method in your subclass of UIDocumnet:
- (id) contentsForType:(NSString *)typeName error:(NSError **)outError
Do you know of any way to delete all of the entries stored in Core Data? My schema should stay the same; I just want to reset it to blank.
Edit
I'm looking to do this programmatically so that a user can essentially hit a reset button.
You can still delete the file programmatically, using the NSFileManager:removeItemAtPath:: method.
NSPersistentStore *store = ...;
NSError *error;
NSURL *storeURL = store.URL;
NSPersistentStoreCoordinator *storeCoordinator = ...;
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
Then, just add the persistent store back to ensure it is recreated properly.
The programmatic way for iterating through each entity is both slower and prone to error. The use for doing it that way is if you want to delete some entities and not others. However you still need to make sure you retain referential integrity or you won't be able to persist your changes.
Just removing the store and recreating it is both fast and safe, and can certainly be done programatically at runtime.
Update for iOS5+
With the introduction of external binary storage (allowsExternalBinaryDataStorage or Store in External Record File) in iOS 5 and OS X 10.7, simply deleting files pointed by storeURLs is not enough. You'll leave the external record files behind. Since the naming scheme of these external record files is not public, I don't have a universal solution yet. – an0 May 8 '12 at 23:00
You can delete the SQLite file - but I choose to do it by purging the tables individually with a functions:
- (void) deleteAllObjects: (NSString *) entityDescription {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:_managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *items = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
for (NSManagedObject *managedObject in items) {
[_managedObjectContext deleteObject:managedObject];
DLog(#"%# object deleted",entityDescription);
}
if (![_managedObjectContext save:&error]) {
DLog(#"Error deleting %# - error:%#",entityDescription,error);
}
}
The reason I chose to do it table by table is that it makes me confirm as I am doing the programming that deleting the contents of the table is sensible and there is not data that I would rather keep.
Doing it this will is much slower than just deleting the file and I will change to a file delete if I this method takes too long.
Updated Solution for iOS 10+
Use NSBatchDeleteRequest to delete all objects in the entity without having to load them into memory or iterate through them.
// create the delete request for the specified entity
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = MyEntity.fetchRequest()
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
// get reference to the persistent container
let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer
// perform the delete
do {
try persistentContainer.viewContext.execute(deleteRequest)
} catch {
print(error.localizedDescription)
}
This code has been updated for iOS 10 and Swift 3. If you need to support iOS 9, see this question.
Sources:
Core Data: Quickest way to delete all instances of an entity (includes Objective-C code)
What's New in Core Data (WWDC 2015 video)
What's New in Core Data (WWDC 2016 video)
How to Use Core Data in iOS 10
What’s new in Core Data Swift 3.0
I've written a clearStores method that goes through every store and delete it both from the coordinator and the filesystem (error handling left aside):
NSArray *stores = [persistentStoreCoordinator persistentStores];
for(NSPersistentStore *store in stores) {
[persistentStoreCoordinator removePersistentStore:store error:nil];
[[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
}
[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
This method is inside a coreDataHelper class that takes care of (among other things) creating the persistentStore when it's nil.
I remove all data from core data on a button Event in a HomeViewController class:
This article helped me so much I figured I'd contribute.
-(IBAction)buttonReset:(id)sender
{
NSLog(#"buttonReset Pressed");
//Erase the persistent store from coordinator and also file manager.
NSPersistentStore *store = [self.persistentStoreCoordinator.persistentStores lastObject];
NSError *error = nil;
NSURL *storeURL = store.URL;
[self.persistentStoreCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
NSLog(#"Data Reset");
//Make new persistent store for future saves (Taken From Above Answer)
if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// do something with the error
}
}
Note that in order to call self.persistentStoreCoordinator I declared a property in the Home View Controller. (Don't worry about the managedObjectContext that I use for saving and loading.)
#property (nonatomic, retain) NSManagedObjectContext * managedObjectContext;
#property (nonatomic, retain) NSPersistentStoreCoordinator * persistentStoreCoordinator;
Then in the AppDelegate ApplicationDidFinishLaunching right below creating a HomeViewController I have :
homeViewController = [[HomeViewController alloc] initWithNibName:#"HomeViewController" bundle:nil];
homeViewController.managedObjectContext = self.managedObjectContext;
homeViewController.persistentStoreCoordinator = self.persistentStoreCoordinator;
iOS9+, Swift 2
Delete all objects in all entities
func clearCoreDataStore() {
let entities = managedObjectModel.entities
for entity in entities {
let fetchRequest = NSFetchRequest(entityName: entity.name!)
let deleteReqest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try context.executeRequest(deleteReqest)
} catch {
print(error)
}
}
}
MagicalRecord makes this very easy.
[MyCoreDataObject MR_truncateAll];
[Late answer in response to a bounty asking for newer responses]
Looking over earlier answers,
Fetching and deleting all items, as suggested by #Grouchal and others, is still an effective and useful solution. If you have very large data stores then it might be slow, but it still works very well.
Simply removing the data store is, as you and #groundhog note, no longer effective. It's obsolete even if you don't use external binary storage because iOS 7 uses WAL mode for SQLite journalling. With WAL mode there may be (potentially large) journal files sitting around for any Core Data persistent store.
But there's a different, similar approach to removing the persistent store that does work. The key is to put your persistent store file in its own sub-directory that doesn't contain anything else. Don't just stick it in the documents directory (or wherever), create a new sub-directory just for the persistent store. The contents of that directory will end up being the persistent store file, the journal files, and the external binary files. If you want to nuke the entire data store, delete that directory and they'll all disappear.
You'd do something like this when setting up your persistent store:
NSURL *storeDirectoryURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"persistent-store"];
if ([[NSFileManager defaultManager] createDirectoryAtURL:storeDirectoryURL
withIntermediateDirectories:NO
attributes:nil
error:nil]) {
NSURL *storeURL = [storeDirectoryURL URLByAppendingPathComponent:#"MyApp.sqlite"];
// continue with storeURL as usual...
}
Then when you wanted to remove the store,
[[NSFileManager defaultManager] removeItemAtURL:storeDirectoryURL error:nil];
That recursively removes both the custom sub-directory and all of the Core Data files in it.
This only works if you don't already have your persistent store in the same folder as other, important data. Like the documents directory, which probably has other useful stuff in it. If that's your situation, you could get the same effect by looking for files that you do want to keep and removing everything else. Something like:
NSString *docsDirectoryPath = [[self applicationDocumentsDirectory] path];
NSArray *docsDirectoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:docsDirectoryPath error:nil];
for (NSString *docsDirectoryItem in docsDirectoryContents) {
// Look at docsDirectoryItem. If it's something you want to keep, do nothing.
// If it's something you don't recognize, remove it.
}
This approach may be error prone. You've got to be absolutely sure that you know every file you want to keep, because otherwise you might remove important data. On the other hand, you can remove the external binary files without actually knowing the file/directory name used to store them.
Here is combined solution for purging Core Data.
- (void)deleteAllObjectsInCoreData
{
NSArray *allEntities = self.managedObjectModel.entities;
for (NSEntityDescription *entityDescription in allEntities)
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entityDescription];
fetchRequest.includesPropertyValues = NO;
fetchRequest.includesSubentities = NO;
NSError *error;
NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(#"Error requesting items from Core Data: %#", [error localizedDescription]);
}
for (NSManagedObject *managedObject in items) {
[self.managedObjectContext deleteObject:managedObject];
}
if (![self.managedObjectContext save:&error]) {
NSLog(#"Error deleting %# - error:%#", entityDescription, [error localizedDescription]);
}
}
}
If you want to delete all objects and do not want to delete the backing files, you can use following methods:
- (void)deleteAllObjectsInContext:(NSManagedObjectContext *)context
usingModel:(NSManagedObjectModel *)model
{
NSArray *entities = model.entities;
for (NSEntityDescription *entityDescription in entities) {
[self deleteAllObjectsWithEntityName:entityDescription.name
inContext: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];
NSLog(#"Deleted %#", entityName);
}
}
Beware that it may be very slow (depends on how many objects are in your object graph).
If you want to go the delete all objects route (which is much simpler than tearing down the Core Data stack, but less performant), than this is a better implementation:
- (void)deleteAllManagedObjectsInModel:(NSManagedObjectModel *)managedObjectModel context:(NSManagedObjectContext *)managedObjectContext
{
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
[managedObjectContext performBlockAndWait:^{
for (NSEntityDescription *entity in managedObjectModel) {
NSFetchRequest *fetchRequest = [NSFetchRequest new];
[fetchRequest setEntity:entity];
[fetchRequest setIncludesSubentities:NO];
NSArray *objects = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
for (NSManagedObject *managedObject in objects) {
[managedObjectContext deleteObject:managedObject];
}
}
[managedObjectContext save:nil];
}];
}];
[operation setCompletionBlock:^{
// Do stuff once the truncation is complete
}];
[operation start];
}
This implementation leverages NSOperation to perform the deletion off of the main thread and notify on completion. You may want to emit a notification or something within the completion block to bubble the status back to the main thread.
iOS 10 + Swift 3 solution:
func clearCoreDataStore() {
let delegate = UIApplication.shared.delegate as! AppDelegate
let context = delegate.persistentContainer.viewContext
for i in 0...delegate.persistentContainer.managedObjectModel.entities.count-1 {
let entity = delegate.persistentContainer.managedObjectModel.entities[i]
do {
let query = NSFetchRequest<NSFetchRequestResult>(entityName: entity.name!)
let deleterequest = NSBatchDeleteRequest(fetchRequest: query)
try context.execute(deleterequest)
try context.save()
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
abort()
}
}
}
Iterates through all of the core data entities and clears them
Swift 4/5, iOS 9+
Rebuilding the whole CoreData SQLite file will make sure all data is erased, therefore all entities are deleted. Just call deleteAndRebuild().
class CoreDataStack {
// Change this
static let datamodelName = "ProjectName"
static let storeType = "sqlite"
static let persistentContainer = NSPersistentContainer(name: datamodelName)
private static let url: URL = {
let url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("\(datamodelName).\(storeType)")
assert(FileManager.default.fileExists(atPath: url.path))
return url
}()
static func loadStores() {
persistentContainer.loadPersistentStores(completionHandler: { (nsPersistentStoreDescription, error) in
if let error = error {
fatalError(error.localizedDescription)
}
})
}
static func deleteAndRebuild() {
try! persistentContainer.persistentStoreCoordinator.destroyPersistentStore(at: url, ofType: storeType, options: nil)
loadStores()
}
}
Thanks for the post. I followed it and it worked for me. But I had another issue that was not mentioned in any of the replies. So I am not sure if it was just me.
Anyway, thought I would post here the problem and my way that solved it.
I had a few records in the database, I wanted to purge everything clean before write new data to the db, so I did everything including
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
and then used managedObjectContext to access the database (supposed to be empty by now), somehow the data was still there.
After a while of troubleshooting, I found that I need to reset managedObjectContext, managedObject, managedObjectModel and
persistentStoreCoordinator, before I use managedObjectContext to access the dabase. Now I have a clean database to write to.
Here is a somewhat simplified version with less calls to AppDelegate self and the last bit of code that was left out of the top rated answer. Also I was getting an error "Object's persistent store is not reachable from this NSManagedObjectContext's coordinator" so just needed to add that back.
NSPersistentStoreCoordinator *storeCoordinator = [self persistentStoreCoordinator];
NSPersistentStore *store = [[storeCoordinator persistentStores] lastObject];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"dataModel"];
NSError *error;
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
if (storeCoordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:storeCoordinator];
}
swift solution:
class func deleteAllManagedObjects() {
let modelURL = NSBundle.mainBundle().URLForResource("some string", withExtension: "mom")
let mom = NSManagedObjectModel(contentsOfURL: modelURL)
for entityName in mom.entitiesByName.keys {
let fr = NSFetchRequest(entityName: entityName as String)
let a = Utility.managedObjectContext().executeFetchRequest(fr, error: nil) as [NSManagedObject]
for mo in a {
Utility.managedObjectContext().deleteObject(mo)
}
}
Utility.managedObjectContext().save(nil)
}
As a quick reference to save searching elsewhere - recreating the persistent store after deleting it can be done with:
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// do something with the error
}
Several good answers to this question. Here's a nice concise one. The first two lines delete the sqlite database. Then the for: loop deletes any objects in the managedObjectContext memory.
NSURL *storeURL = [[(FXYAppDelegate*)[[UIApplication sharedApplication] delegate] applicationDocumentsDirectory] URLByAppendingPathComponent:#"AppName.sqlite"];
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
for (NSManagedObject *ct in [self.managedObjectContext registeredObjects]) {
[self.managedObjectContext deleteObject:ct];
}
Here's a version that deletes every record in every table you have.
Swift 4
static func resetDatabase() {
do {
try dataStore.persistentStoreCoordinator.managedObjectModel.entities.forEach { (entity) in
if let name = entity.name {
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: name)
let request = NSBatchDeleteRequest(fetchRequest: fetch)
try mainContext.execute(request)
}
}
try mainContext.save()
} catch {
print("error resenting the database: \(error.localizedDescription)")
}
}
you can also find all the entity names, and delete them by name. Its a longer version but works well, that way you dont have to work with persistence store
- (void)clearCoreData
{
NSError *error;
NSEntityDescription *des = [NSEntityDescription entityForName:#"Any_Entity_Name" inManagedObjectContext:_managedObjectContext];
NSManagedObjectModel *model = [des managedObjectModel];
NSArray *entityNames = [[model entities] valueForKey:#"name"];
for (NSString *entityName in entityNames){
NSFetchRequest *deleteAll = [NSFetchRequest fetchRequestWithEntityName:entityName];
NSArray *matches = [self.database.managedObjectContext executeFetchRequest:deleteAll error:&error];
}
if (matches.count > 0){
for (id obj in matches){
[_managedObjectContext deleteObject:obj];
}
[self.database.managedObjectContext save:&error];
}
}
for "Any_Entity_Name" just give any one of your entity's name, we only need to figure out the entity description your entities are within. ValueForKey#"name" will return all the entity names. Finally, dont forget to save.
The accepted answer is correct with removing URL by NSFileManager is correct, but as stated in iOS 5+ edit, the persistent store is not represented only by one file. For SQLite store it's *.sqlite, *.sqlite-shm and *.sqlite-wal ... fortunately since iOS 7+ we can use method
[NSPersistentStoreCoordinator
+removeUbiquitousContentAndPersistentStoreAtURL:options:error:]
to take care of removal, so the code should be something like this:
NSPersistentStore *store = ...;
NSError *error;
NSURL *storeURL = store.URL;
NSString *storeName = ...;
NSPersistentStoreCoordinator *storeCoordinator = ...;
[storeCoordinator removePersistentStore:store error:&error];
[NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:storeURL.path options:#{NSPersistentStoreUbiquitousContentNameKey: storeName} error:&error];
One other method (apart from a delete batch request) I often use (based on app requirement) is to reset the persistent store. The implementation looks like this for iOS 10+ and Swift (assuming you have a CoreDataManager class):
let persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "<Data-Model-Name>“)
container.loadPersistentStores(completionHandler: { (storeDescription, err) in
if let err = err {
fatalError("loading of store failed: \(err)")
}
})
return container
}()
func resetPersistentStore() {
if let persistentStore = persistentContainer.persistentStoreCoordinator.persistentStores.last {
let storeURL = persistentContainer.persistentStoreCoordinator.url(for: persistentStore)
do {
try persistentContainer.persistentStoreCoordinator.destroyPersistentStore(at: storeURL, ofType: NSSQLiteStoreType, options: nil)
} catch {
print("failed to destroy persistent store:", error.localizedDescription)
}
do {
try persistentContainer.persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
} catch {
print("failed to re-add persistent store:", error.localizedDescription)
}
}
}
One advantage of this method is that it’s more straightforward especially when you have loads of data record for numerous entities in your core data. In which case a delete batch request would be memory intensive.
Swift 5.1 Solution
public static func reset() {
let coordinator = _persistentContainer.persistentStoreCoordinator
for store in coordinator.persistentStores where store.url != nil {
try? coordinator.remove(store)
try? FileManager.default.removeItem(atPath: store.url!.path)
}
}
Works with all versions. Pass entity name and iterate through to delete all the entries and save the context.
func deleteData(entityToFetch: String, completion: #escaping(_ returned: Bool) ->()) {
var context = NSManagedObjectContext()
if #available(iOS 10.0, *) {
context = self.persistentContainer.viewContext
} else {
context = self.managedObjectContext
}
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
fetchRequest.entity = NSEntityDescription.entity(forEntityName: entityToFetch, in: context)
fetchRequest.includesPropertyValues = false
do {
let results = try context.fetch(fetchRequest) as! [NSManagedObject]
for result in results {
context.delete(result)
}
try context.save()
completion(true)
} catch {
completion(false)
print("fetch error -\(error.localizedDescription)")
}
}
There seems to be two approaches:
Say you have a typical singleton for your core data stack.
import CoreData
public let core = Core.shared
public final class Core {
static let shared = Core()
var container: NSPersistentContainer!
private init() {
container = NSPersistentContainer(name: "stuff")
//deleteSql()
container.loadPersistentStores { storeDescription, error in
if let error = error { print("Error loading... \(error)") }
}
//deleteAll()
}
func saveContext() { // typical save helper
if container.viewContext.hasChanges {
do { try container.viewContext.save()
} catch { print("Error saving... \(error)") }
}
}
then ...
func deleteSql() {
let url = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask)[0].appendingPathComponent( "stuff.sqlite" )
guard FileManager.default.fileExists(atPath: url.path) else {
print("nothing to delete!")
return
}
do {
try container.persistentStoreCoordinator.destroyPersistentStore(
at: url, ofType: "sqlite", options: nil)
print("totally scorched the sql file. you DO now have to LOAD again")
}
catch {
print("there was no sql file there!")
}
}
func deleteAll() { // courtesy #Politta
for e in container.persistentStoreCoordinator.managedObjectModel.entities {
let r = NSBatchDeleteRequest(
fetchRequest: NSFetchRequest(entityName: e.name ?? ""))
let _ = try? container.viewContext.execute(r)
}
saveContext()
print("conventionally deleted everything from within core data. carry on")
}
}
.
1. scorch the sql file
Courtesy the excellent #J.Doe answer. You completely destroy the sql file.
You must to do this
before loading core data, ie, after creating the container, but
before actually loading the stores.)
(Notice the example line of code "//deleteSql()" is just before initialization.)
2. delete everything one by one within core data
Courtesy the excellent #Politta answer. You could do this at any time once core data is up and running.
(Notice the example line of code "//deleteAll()" is after initialization.)
Approach one is probably more useful during development. Approach two is probably more useful in production (in the relatively unusual case that for some reason you need to wipe everything).
Delete the persistent store file and setup a new persistent store coordinator?
Delete sqlite from your fileURLPath and then build.
Assuming you are using MagicalRecord and have a default persistence store:
I don't like all the solutions that assume certain files to exist and/or demand entering the entities names or classes. This is a Swift(2), safe way to delete all the data from all the entities. After deleting it will recreate a fresh stack too (I am actually not sure as to how neccessery this part is).
It's godo for "logout" style situations when you want to delete everything but have a working store and moc to get new data in (once the user logs in...)
extension NSManagedObject {
class func dropAllData() {
MagicalRecord.saveWithBlock({ context in
for name in NSManagedObjectModel.MR_defaultManagedObjectModel().entitiesByName.keys {
do { try self.deleteAll(name, context: context) }
catch { print("⚠️ ✏️ Error when deleting \(name): \(error)") }
}
}) { done, err in
MagicalRecord.cleanUp()
MagicalRecord.setupCoreDataStackWithStoreNamed("myStoreName")
}
}
private class func deleteAll(name: String, context ctx: NSManagedObjectContext) throws {
let all = NSFetchRequest(entityName: name)
all.includesPropertyValues = false
let allObjs = try ctx.executeFetchRequest(all)
for obj in allObjs {
obj.MR_deleteEntityInContext(ctx)
}
}
}
Use this
+(NSArray *)fetchDataFromEntity:(NSString *)entityName context:(NSManagedObjectContext *)context
{
NSFetchRequest * fetchRequest =[[NSFetchRequest alloc] init];
NSEntityDescription * CategoriesEntity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[fetchRequest setEntity:CategoriesEntity];
NSError * error;
NSInteger count = [context countForFetchRequest:fetchRequest error:&error];
if (count && count>0) {
NSArray * fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects && fetchedObjects.count>0) {
return fetchedObjects;
}else
return nil;
}
else
return nil;
}
+ (void)deleteObjectsOfArray:(NSMutableArray*)ary context:(NSManagedObjectContext *)context {
for (NSManagedObject * obj in ary) {
[context deleteObject:obj];
}
NSError *saveError = nil;
[context save:&saveError];
}
+ (void)deleteEntity:(NSString *)entityName context:(NSManagedObjectContext *)context {
NSArray *listArray = [self fetchDataFromEntity:entityName context:context];
[self deleteObjectsOfArray:[NSMutableArray arrayWithArray:listArray] context:context];
}
I took Grouchal's code and to speed it up I used enumeration with concurrent mode (NSEnumerationConcurrent), it got a bit faster compared to for loop (in my app I added this feature for Testers so that they can clear data and do testcases rather than delete and install app)
- (void)resetObjects
{
[self deleteAllObjectsInEntity:#"Entity1"];
[self deleteAllObjectsInEntity:#"Entity2"];
[self deleteAllObjectsInEntity:#"Entity3"];
[self deleteAllObjectsInEntity:#"Entity4"];
}
-(void) deleteAllObjectsInEntity:(NSString*) entityName
{
MainDataContext *coreDataContext = [MainDataContext sharedInstance];
NSManagedObjectContext *currentContext = coreDataContext.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:currentContext];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *items = [currentContext executeFetchRequest:fetchRequest error:&error];
[items enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSManagedObject * obj, NSUInteger idx, BOOL *stop) {
[currentContext deleteObject:obj];
}];
if (![currentContext save:&error]) {
NSLog(#"Error deleting %# - error:%#",entityName,error);
}
}