NSFileManager delete contents of directory

后端 未结 9 1837
你的背包
你的背包 2021-01-30 17:13

How do you delete all the contents of a directory without deleting the directory itself? I want to basically empty a folder yet leave it (and the permissions) intact.

9条回答
  •  甜味超标
    2021-01-30 17:37

    You can extend the NSFileManager like this:

    extension NSFileManager {
      func clearFolderAtPath(path: String) -> Void {
          for file in subpathsOfDirectoryAtPath(path, error: nil) as? [String] ?? []  {
              self.removeItemAtPath(path.stringByAppendingPathComponent(file), error: nil)
          }
      }
    }
    

    Then, you can clear the folder like this: NSFileManager.defaultManager().clearFolderAtPath("the folder's path")

提交回复
热议问题