NSFileManager:试图删除文件,但它说它们不存在

NSFileManager: Trying to delete files, but it says they don't exist

我正在尝试删除缓存目录中的文件。但是,当我尝试删除单个文件夹时,我收到一条错误消息,指出该文件不存在,即使我知道它存在。因此,我尝试使用 for 循环删除缓存目录中的所有文件。

do {
        for file in try NSFileManager.defaultManager().contentsOfDirectoryAtPath(cacheFolderPath) where !file.hasPrefix("."){
            try NSFileManager.defaultManager().removeItemAtPath(file)
        }
        print("Cache cleared successfully.")
    }
    catch let error as NSError {
        print(error.localizedDescription)
        if let reason = error.localizedFailureReason {
            print(reason)
        }
    }
}

但是,此代码打印如下:

"CategoryThumbnails" couldn't be removed.
The file doesn't exist.

嗯,它显然是存在的,因为它是contentsOfDirectoryAtPath方法发现的!怎么可能不存在呢?有人知道这里发生了什么吗?我该如何清除缓存?

contentsOfDirectoryAtPath 的结果是给定文件夹中的文件列表。但是这些结果中的每一个都不是完整的路径。

要删除每个 file,您需要将 file 附加到 cacheFolderPath。然后将该完整路径传递给 removeItemAtPath.

另一种解决方案是使用 NSFileManager 的其他文件夹枚举方法之一,即 return 完整 URL,并让您提供跳过隐藏文件的选项。