【问题标题】:Delete all files and folder from a certain folder从某个文件夹中删除所有文件和文件夹
【发布时间】:2011-05-09 10:29:42
【问题描述】:

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

我尝试了几个代码 sn-ps,但没有一个删除文件夹

我的方法:

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

}

【问题讨论】:

标签: iphone cocoa nsfilemanager


【解决方案1】:
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.
    }
}

希望对你有帮助

【讨论】:

  • 您是否打算将documentsDirectory 变成NSDocumentDirectory
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多