objective-c - 递归列出并存储目录内容

标签 objective-c cocoa

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

但是,我想将我的发现存储到对象层次结构中(例如,具有isLeaf的自定义 FileOrDirectory 类的对象, 计数属性)。

我需要将目录和文件结构预先加载到这样的对象层次结构中,以便使用 NSTreeController 等执行我想要的操作。我想这里最棘手的事情是让对象层次结构中的 children 属性正确。

有什么想法吗?

最佳答案

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

这是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;
}

关于objective-c - 递归列出并存储目录内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2986199/

相关文章:

ios - NSData 与 NSValue?如何在 sendMIDISysExEvent :(NSData *)midiData 中封装 C 结构

objective-c - 有没有一种简单的方法来更改 NSTableView 的字体大小?

ios - 使用核心图更新图形的特定部分?

ios - 为什么 UIViewController.UIView 对子 UIViewLabel 的约束抛出错误 "Invalid pairing of layout attributes"?

macos - 导出的 UTI 未被 macOS 拾取

ios - 从日历组件创建 NSDate 时出现 1 错误

macos - 使用窗口 id 在屏幕上创建一个窗口

objective-c - 在 Cocoa Desktop 中切换 "Show/Hide"菜单项的最佳方法

cocoa - XCode>仪器>泄漏 - "gather leaked memory contents"数据在哪里?

objective-c - 非 GC 应用程序中的内存管理 OS X __block 变量分配