删除某个文件夹中的所有文件和文件夹
我有一个 /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.
}
}*/
}
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.
}
}*/
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
希望这有帮助
Hope this helps
您的代码 (
[fm removeItemAtPath:directory error:&error];
) 应该可以做到这一点。如果没有,请检查它返回的错误。如果没有错误,但您仍然看到文件/子文件夹 - 提交错误报告!http://开发人员。 apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html
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