Delete All Files in Documents Directory
The first approach I took was to loop through all the files, building a path to each, one by one:
- // Path to the Documents directory
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- if ([paths count] > 0)
- {
- NSError *error = nil;
- NSFileManager *fileManager = [NSFileManager defaultManager];
- // Print out the path to verify we are in the right place
- NSString *directory = [paths objectAtIndex:0];
- NSLog(@"Directory: %@", directory);
- // For each file in the directory, create full path and delete the file
- for (NSString *file in [fileManager contentsOfDirectoryAtPath:directory error:&error])
- {
- NSString *filePath = [directory stringByAppendingPathComponent:file];
- NSLog(@"File : %@", filePath);
- BOOL fileDeleted = [fileManager removeItemAtPath:filePath error:&error];
- if (fileDeleted != YES || error != nil)
- {
- // Deal with the error...
- }
- }
- }
The code above works fine, however, I was interested in something that didn’t build each path separately – the code below deletes all the files in one fell swoop:
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- if ([paths count] > 0)
- {
- NSLog(@"Path: %@", [paths objectAtIndex:0]);
- NSError *error = nil;
- NSFileManager *fileManager = [NSFileManager defaultManager];
- // Remove Documents directory and all the files
- BOOL deleted = [fileManager removeItemAtPath:[paths objectAtIndex:0] error:&error];
- if (deleted != YES || error != nil)
- {
- // Deal with the error...
- }
To get things working again, I changed up the code above to create the Documents directory:
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- if ([paths count] > 0)
- {
- NSLog(@"Path: %@", [paths objectAtIndex:0]);
- NSError *error = nil;
- NSFileManager *fileManager = [NSFileManager defaultManager];
- // Remove all files in the documents directory
- BOOL deleted = [fileManager removeItemAtPath:[paths objectAtIndex:0] error:&error];
- if (deleted != YES || error != nil)
- {
- // Deal with the error...
- }
- else
- // Recreate the Documents directory
- [fileManager createDirectoryAtPath:[paths objectAtIndex:0] withIntermediateDirectories:NO attributes:nil error:&error];
- }
No comments:
Post a Comment