views:

90

answers:

1

I know how to recursively list directory contents. I will be using Snow Leopard's enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: method to do this.

However I want to store my findings into a object hierarchy (of, say, objects of a custom FileOrDirectory class that has isLeaf, children, and count attributes).

I need to pre-load the directory and file structure into such a object hierarchy, in order to do whatever I want with NSTreeController and whatnot. I guess the trickiest thing here is to get the children attribute correct in the object hierarchy.

Any ideas?

+1  A: 

If I understand your question correctly, you could solve this by writing a recursive function that takes the current node (a file or a folder) and returns an object representing it's structure.

This is Java, but maybe it conveys my idea. I have omitted isLeaf and count, as their values can be derived from the 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;
}
Lauri Lehtinen
I understand you. Thanks. However, I take it that the built-in Cocoa method for *recursively* listing contents is not suited for my purposes? I suppose I do have to indeed have to do the recursion (doing an "if directory" check) by myself to be able to properly capture the hierarchy I want? Am I right? Do Cocoa developers agree?
Enchilada
What does the built-in functionality give you? A textual representation of the hierarchy? In that case, the alternative would be to write code that parses the list and builds the kind of representation you need on the go. I could we way off, not a Cocoa guy sorry.
Lauri Lehtinen