Delete all files and folder from a certain folder

10,581

Solution 1

Your code ([fm removeItemAtPath:directory error:&error];) should do it. If it doesn't, inspect the error it returns. If there's no error, but you still see files/subfolders - file a bug report!

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html

Solution 2

NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"urDirectory/"];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
    BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error];
    if (!success || error) {
        // it failed.
    }
}

Hope this helps

Share:
10,581
SnK
Author by

SnK

iOs Developer

Updated on June 22, 2022

Comments

  • SnK
    SnK almost 2 years

    I have a /Documents/Images folder , in that folder are several other folders named after years , in those folders i have images. I want to delete everything from the images folder ( including the folders and the images in these folders).

    I tried several code snippets but none delete the folders

    my method:

    - (void) clearCache:(NSString *) folderName{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *directory = [documentsDirectoryPath stringByAppendingPathComponent:folderName];
    NSLog(@"Removing items at path: %@",directory);
        NSError *error = nil;
    BOOL succes = [fm removeItemAtPath:directory error:&error];
    
    /*for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
        //BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error];
        BOOL success = [fm removeItemAtPath:[directory stringByAppendingPathComponent:file] error:&error];
        if (!success || error) {
            // it failed.
        }
    }*/
    

    }

  • Basil Bourque
    Basil Bourque about 10 years
    Did you intend documentsDirectory to be NSDocumentDirectory?