删除某个文件夹中的所有文件和文件夹

时间:2011-05-09 10:29:42

标签: iphone cocoa nsfilemanager

我有一个/ Documents / Images文件夹,在该文件夹中是几个以年命名的其他文件夹,在那些文件夹中我有图像。我想删除图像文件夹中的所有内容(包括文件夹和这些文件夹中的图像)。

我尝试了几个代码段但没有删除文件夹

我的方法:

- (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.
    }
}*/

}

2 个答案:

答案 0 :(得分:8)

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.
    }
}

希望这有帮助

答案 1 :(得分:5)

您的代码([fm removeItemAtPath:directory error:&error];)应该这样做。如果没有,请检查它返回的错误。如果没有错误,但您仍然看到文件/子文件夹 - 提交错误报告!

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