Removing non-empty folders and specific file types
To delete a directory tree (or file) use -[NSFileManager removeItemAtPath:error:]
. This removes files directly (and deletes all of them ); if you want to move an item to the cart instead use NSWorkspaceRecycleOperation
.
How to delete only files with certain extensions: Get each path pathExtension
and use caseInsensitiveCompare:
to compare it to the ones you are looking for, then delete the file if it is on your hit list.
If you want to merge the two (that is, delete only files in the directory tree that have a given extension), you will need to get the directory enumerator from NSFileManager and traverse the directory tree yourself, deleting the files one at a time.
source to share
To delete files with a specific extension ..
At least one way. This example simply searches the application documents directory for any jpg files and removes them.
NSFileManager *fManager = [NSFileManager defaultManager];
NSString *dir = [self applicationDocumentsDirectory];
NSError *error;
NSArray *files = [fManager contentsOfDirectoryAtPath:dir error:&error];
for (NSString *file in files) {
if ([[[file pathExtension] lowercaseString] isEqualToString: @"jpg"])
{
[fManager removeItemAtPath: [dirstringByAppendingPathComponent:file] error:&error];
NSLog(@"removed: %@",file);
}
if (error) {
//deal with it
}
}
source to share