objective-c - 删除iOS中的空文件夹?

标签 objective-c ios5 nsfilemanager

我的应用程序的文档文件夹中有很多空的临时文件夹。

如何将它们全部删除?

我尝试过:

NSArray *folders = [[NSFileManager defaultManager]contentsOfDirectoryAtURL:[self applicationDocumentsDirectory] includingPropertiesForKeys:[NSArray arrayWithObject:@"NSURLIsDirectoryKey"] options:0 error:nil];
if (folders) {
    for (NSURL *url in folders) {
        [[NSFileManager defaultManager]removeItemAtURL:url error:nil];
    }
}

但它会删除所有内容,而不仅仅是文件夹

最佳答案

此代码片段仅删除目录

NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (NSString *file in files) {
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file];
    NSError *error;
    if ([[fileManager contentsOfDirectoryAtPath:fullPath error:&error] count]==0) {
        // check if number of files == 0 ==> empty directory
        if (!error) { 
            // check if error set (fullPath is not a directory and we should leave it alone)
            [fileManager removeItemAtPath:fullPath error:nil];
        }
    }
}

如果您只想删除所有目录(非空),则代码片段可以简化为:

NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (NSString *file in files) {
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file];
    if ([fileManager contentsOfDirectoryAtPath:fullPath error:nil])
        [fileManager removeItemAtPath:fullPath error:nil];
}

关于objective-c - 删除iOS中的空文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9966696/

相关文章:

iphone - Xcode build设置

objective-c - 执行选择器 :withObject:afterDelay not working inside viewDidLoad method

objective-c - iOS 中的 XOR 文件加密

ios - 在 iOS 中将大量且频繁的数据写入文件?

ios - Xcode tableview 不显示文本

c# - Apple 的键值编码——有人可以向 C# 开发人员解释为什么我需要这个以及它的作用吗?

objective-c - 动画调整 NSImageView 大小的最有效方法

iOS 7 截取部分 UIView 的屏幕截图

ios - iOS 应用程序的处理流程

swift - 从目录中读取所有文件?