3

I have a feature in my app whereby the User can reset everything on the app by click of a button. At this point, instead of trying to delete all the Core Data relations (Cascade Delete) and other complications, I decided to actually remove the entire UIManagedDocument using this piece of code

-(void)cleanUpDocument
{
   [[NSFileManager defaultManager] removeItemAtPath:[self.document.fileURL path] error:nil];
}

This should remove the Document I assume? But it sometimes throws an error. And the weird part is that, when I try to re-create the Document the next time, I get an error saying "Can't create File, File already Exists". The code that i use to create the Document is this :-

    if (![[NSFileManager defaultManager] fileExistsAtPath:[self.document.fileURL path]]) {
    [self.document saveToURL:self.document.fileURL
            forSaveOperation:UIDocumentSaveForCreating
           completionHandler:nil]
     }

My question is this :- what is the best/correct way to remove/delete an entire UIManagedDocument and start fresh on next successful login?

Thanks in advance.

Anuj Gakhar
  • 681
  • 2
  • 13
  • 26

2 Answers2

0

I just had the same issue and tried exactly your approach at first, only to be greeted by similar errors. From what I gather, it's not the best (or at least not necessary) to delete the entire UIManagedDocument, but rather only the underlying persistent store (while keeping this managedObjectContext in sync, of course).

This answer worked for me: https://stackoverflow.com/a/8467628/671915

Community
  • 1
  • 1
Ryan Artecona
  • 5,953
  • 3
  • 19
  • 18
0

The problem is that you're removing the file while some objects still hold a reference to it and are keeping it open.

The correct solution is to do this:

[document closeWithCompletionHandler:^(BOOL success){
    if([[NSFileManager defaultManager] fileExistsAtPath:[document.fileURL path]]){
        [[NSFileManager defaultManager] removeItemAtURL:document.fileURL error:nil];
    }
entropy
  • 3,134
  • 20
  • 20