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

SnK*_*SnK 1 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.
    }
}*/
Run Code Online (Sandbox Code Playgroud)

}

vis*_*kh7 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.
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助


Ste*_*mer 5

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

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