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

NSE*_*rer 14 iphone objective-c foundation

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

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

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

cml*_*oyd 50

试试这个:

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];
}
Run Code Online (Sandbox Code Playgroud)