0

I'm clearing my app's Documents folder using a NSDirectoryEnumerator. It works, mostly, except that for some reason that I cannot fathom, it leaves 1 file behind. Here's my code:

        NSDirectoryEnumerator * enumerator = [fileMan enumeratorAtURL:[NSURL fileURLWithPath:docsFolder()] includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsSubdirectoryDescendants errorHandler:^BOOL(NSURL *url, NSError *error) {
        NSLog(@"%@,%@",url,error);
        return YES;
    }];
    for (NSURL * fileURL in enumerator) {
        BOOL removed = [fileMan removeItemAtURL:fileURL error:nil];
        NSLog(@"Removed %@:%d",fileURL.path,removed);
    }

The docsFolder() call in the above code is a function which simply returns the app's documents folder, using NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES). I've breakpointed and logged in the error handler, it never hits. I've got a ton of files in there, they all get deleted fine. Except, there's always one file, always the same file, that gets left behind. This is in iOS 8.1, in the Simulator. Even if, for some reason, the file was locked (or whatever else) the error handler should have gotten called, so I'm at a loss as to what is happening.

Could it have something to do with the fact that all the files in the Documents folder are "hard" links to files in a separate folder? What would cause a hard link to not get... unlinked?

Anyone have any ideas why this might be happening?

Dhiraj Gupta
  • 9,704
  • 8
  • 49
  • 54

2 Answers2

0

You are deleting files while enumerating them. This confuses the enumerator. A safer approach would be: enumerate the files and collect their names into an array. After the enumeration ends, go through the array and delete the files.

Andrei Belogortseff
  • 1,861
  • 3
  • 18
  • 26
  • I've tried this approach, but it doesn't cause any difference. I collected all the enumerated URLs in an NSMutableArray and then after finishing the directory enumerator, I deleted using the array. – Dhiraj Gupta Nov 20 '14 at 03:18
0

If you just want to delete everything in a directory, but not the containing directory, try this:

NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
for (NSString *item in directoryContents) {
    [[NSFileManager defaultManager] removeItemAtPath:[path stringByAppendingPathComponent:item] error:nil];
}

Should probably check the errors too.

Jon Shier
  • 12,200
  • 3
  • 35
  • 37