开发者

Delete all files and folder from a certain folder

开发者 https://www.devze.com 2023-03-04 03:06 出处:网络
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 folde

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];
    开发者_Python百科if (!success || error) {
        // it failed.
    }
}*/

}


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消