ios - 在 iOS 上删除包含大量文件的文件夹的性能

标签 ios performance delete-file nsfilemanager

假设我在我的 iOS 应用程序的数据目录中有一个文件夹,其中包含数千个小文件。删除此文件夹(通过 [NSFileManager removeItemAtPath])需要花费大量时间。但在 OS X 上,删除具有相同内容的文件夹非常快。它似乎只是从文件系统中取消链接文件夹。那么为什么 iOS 需要这么长时间?有什么区别?

编辑:在 iPad 3 上,删除 3 个文件夹,每个文件夹包含 5,000 到 9,000 个文件,大约需要 35 秒。在旧版 Retina MBP 上运行的模拟器上,大约需要 1.5 秒。

最佳答案

The hierarchical structure that you see is not "real" -- directories are not physical containers for the files that they appear to contain. The directory hierarchy is a carefully maintained fiction.

Irrelevant aside: The original Mac file system took this a step further -- it made the directory structure totally a visual fiction -- all of the files were at the root of the (3.5") floppy) disk, and only seemed to be arranged in folders. Thankfully this was supplanted by HFS.

It is better to think of directories/folders as a special kind of file that contains an index to a set of files that it is going to pretend to contain.

Conceptually, this works much like classical Cocoa memory management. Each (directory/object) "owns" a set of (files/objects) by reference ("retains" the (file/object)).

When you delete a file from a directory, it is "released". If no other directory has an ownership claim on that file, it is "dealloc'ed".

Your (folder/object) doesn't contain the objects that it "owns". It doesn't really even "own" them -- it just has a "ownership claim" on them.

From Wikipedia's article about Hard Links:

"a hard link is a directory entry that associates a name with a file on a file system. A directory is itself a special kind of file that contains a list of such entries."

请注意,由于使用了硬链接(hard link),因此可能只有一个 可以出现在多个目录中的物理文件。每一个 这些目录拥有对“真实”文件的引用。每个引用 和其他任何东西一样“真实”。所有引用文献都必须“取消链接” 要标记为已删除的文件。

"file"甚至可以在不同的地方有不同的“名字” 目录!

硬链接(hard link)是文件系统功能的链锯——功能强大,但 可能相当危险。请注意,OSX GUI 不提供任何方法 产生硬链接(hard link),甚至是符号链接(symbolic link)。

来自 this email list item .

现在关于 iOS

[NSFileManager removeItemAtPath: error:], 它在下面做了什么 引擎盖是他们遍历子目录和文件并删除 他们先。这需要一些时间。如果可能的话,我很感兴趣 立即执行此操作,甚至无需隐式递归。只需删除 目录和文件和子目录会消失吗?

你能做的是

  1. 如果您担心这会花费时间并且您需要即时结果,您可以重命名该文件夹(这实际上是即时的)然后删除重命名的文件夹及其在后台线程中的内容。

  2. 如果时间有限,如果没有问题,请尝试在后台线程中运行删除过程。

关于ios - 在 iOS 上删除包含大量文件的文件夹的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22100528/

相关文章:

ios - 在获取信息时防止我的功能阻塞功能

java - 如何使用 Java 将 >1000 个 xml 文件合并为一个文件

c# - 如果只需要读取一次,则在查找后从 C# 字典中删除项目的任何性能优势

c++ - 类型转换是否会消耗额外的 CPU 周期

c - nftw 线程安全

ios - 无法附加到 pid : “16541” unable to attach ios simulator

ios - 如何将字符串转换为数据

ios - 对 UIImageView 从起点到终点的移动进行动画处理

file - 如何删除文件?

java - 在java中解压缩后删除zip文件