递归列出和存储目录内容

时间:2010-06-06 22:37:29

标签: objective-c cocoa

我知道如何递归列出目录内容。我将使用Snow Leopard的enumeratorAtURL:includesPropertiesForKeys:options:errorHandler:方法来执行此操作。

但是我想我的调查结果存储到对象层次结构(例如,具有 isLeaf 的自定义FileOrDirectory类的对象, 儿童计数属性)。

我需要将目录和文件结构预先加载到这样的对象层次结构中,以便用NSTreeController和诸如此类的东西做我想做的事情。我想这里最棘手的事情是在对象层次结构中使 children 属性正确。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果我正确理解你的问题,你可以通过编写一个递归函数来解决这个问题,该函数接受当前节点(文件或文件夹)并返回一个表示它结构的对象。

这是Java,但它可能传达了我的想法。我省略了isLeafcount,因为它们的值可以从children派生。

class FileOrFolder
{
    String name;
    FileOrFolder[] children;
    boolean isFile;
}

private FileOrFolder traverse(File file)
{
    FileOrFolder fof = new FileOrFolder();
    fof.name = file.getAbsolutePath();
    if (file.isDirectory())
    {
        String[] children = file.list();
        fof.children = new FileOrFolder[children.length];
        for (int i = 0; i < children.length; i++)
        {
            fof.children[i] = traverse(new File(fof.name + "/" + children[i]));
        }
    }
    fof.isFile = file.isFile();
    return fof;
}