如何删除应用程序上的指定目录中的所有文件?

给定一个目录[[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"]如何删除此文件夹中的所有文件?

(假定文档目录path正确)

 NSFileManager *fm = [NSFileManager defaultManager]; NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"]; 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. } } 

如果存在的话,我把它留给你做一些有用的错误。

如果你想删除文件和目录本身,然后使用它没有for循环

 NSFileManager *fm = [NSFileManager defaultManager]; NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos"]; NSError *error = nil; BOOL success = [fm removeItemAtPath:cacheImageDirectory error:&error]; if (!success || error) { // something went wrong } 

对于快速恋人来说也是如此:

  let fm = NSFileManager.defaultManager() do { let folderPath = ... let paths = try fm.contentsOfDirectoryAtPath(folderPath) for path in paths { try fm.removeItemAtPath("\(folderPath)/\(path)") } } catch let error as NSError { print(error.localizedDescription) }