如何删除Documents目录的内容(而不是Documents目录本身)?

时间:2011-01-20 15:50:11

标签: iphone objective-c foundation

我想删除Documents目录中包含的所有文件和目录。

我相信使用 [fileManager removeItemAtPath:documentsDirectoryPath error:nil] 方法也会删除文档目录。

是否有任何方法可以删除目录的内容并将空目录留在那里?

4 个答案:

答案 0 :(得分:47)

试试这个:

NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSError *error = nil;
for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
    [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
}

答案 1 :(得分:3)

Swift 3.x

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
guard let items = try? FileManager.default.contentsOfDirectory(atPath: path) else { return }

for item in items {
    // This can be made better by using pathComponent
    let completePath = path.appending("/").appending(item)
    try? FileManager.default.removeItem(atPath: completePath)
}

答案 2 :(得分:1)

我认为使用URL而不是String会使其更简单:

private func clearDocumentsDirectory() {
    let fileManager = FileManager.default
    guard let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

    let items = try? fileManager.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil)
    items?.forEach { item in
        try? fileManager.removeItem(at: item)
    }
}

答案 3 :(得分:0)

其他解决方案只删除表面级别,这将迭代地撕裂到子目录并清除它们。

此外,一些答案使用 removeItem: 和文件本身的本地路径,而不是完整路径,这是操作系统正确删除所需的路径。


只需拨打[self purgeDocuments];

+(void)purgeDocuments __deprecated_msg("For debug purposes only") {
    NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    [self purgeDirectory:documentDirectoryPath];
}

+(void)purgeDirectory:(NSString *)directoryPath __deprecated_msg("For debug purposes only") {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:directoryPath error:&error];
    for (NSString *itemPath in directoryContent) {
        NSString *itemFullPath = [NSString stringWithFormat:@"%@/%@", directoryPath, itemPath];
        BOOL isDir;
        if ([fileManager fileExistsAtPath:itemFullPath isDirectory:&isDir]) {
            if (isDir) {
                [self purgeDirectory:itemFullPath];//subdirectory
            } else {
                [fileManager removeItemAtPath:itemFullPath error:&error];
            }
        }
    }
}