【问题标题】:iOS Read multiple subdirectoriesiOS 读取多个子目录
【发布时间】:2013-04-10 22:05:14
【问题描述】:

我正在尝试读取目录,然后获取这些目录中文件的路径。问题是,我不知道一个文件夹里可能有多少个子目录,还有这段代码

NSString *path;
if ([[NSFileManager defaultManager] fileExistsAtPath:[[self downloadsDir] stringByAppendingPathComponent:[tableView cellForRowAtIndexPath:indexPath].textLabel.text]]) {
    path = [[self downloadsDir] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [tableView cellForRowAtIndexPath:indexPath].textLabel.text]];
}
else{
    for (NSString *subdirs in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self downloadsDir] error:nil]) {
        BOOL dir;
        [[NSFileManager defaultManager] fileExistsAtPath:[[self downloadsDir] stringByAppendingPathComponent:subdirs] isDirectory:&dir];
        if (dir) {
            for (NSString *f in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[self downloadsDir] stringByAppendingPathComponent:subdirs] error:nil]) {
                if ([f isEqualToString:[tableView cellForRowAtIndexPath:indexPath].textLabel.text]) {
                    path = [[self downloadsDir] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", subdirs, f]];
                }
            }
        }
    }
}

最多只能读取一个子目录,并为我提供我正在寻找的文件的路径。我找不到比这更好的方法来获取多个子目录以及这些目录中文件的路径。有人能帮忙吗?这就是我想要做的事情

+Downloads Folder+
    +File1+ //I can get the path for this
    +Directory1+ 
         +Directory2+ 
             +File3+ // I want to get the path for this, but don't know how
         +File2+ // I can get the path for this

我觉得如果我只是不断重复获取目录内容的 for 循环,我最终可能会遇到问题。

【问题讨论】:

  • 通常你会使用递归或队列来做到这一点。
  • @Dave 我认为递归是最好的方法,但我不知道该怎么做。
  • 这并不难,只要把你的代码放在一个函数中,让它在找到一个目录时用一个新目录调用自己来搜索。队列更好,但递归更直观。
  • 哦,注意不要关注...,我假设您使用的是健全的文件系统(即没有硬链接)

标签: iphone ios objective-c directory nsfilemanager


【解决方案1】:

有一个名为recursion 的概念,通常应用于此类问题。 基本上,您为每个子目录调用该方法,然后依次调用 它适用于每个子子目录,依此类推。

重要的是你定义了一个停止点,所以它不会永远持续下去。似乎一个好的停止点是一个文件或一个空目录。

在伪代码中:

method storePaths(directory)
    for each element in  directory
        if element is a file
            store path
        else if element not empty directory
             call storePaths(element)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 2020-12-02
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    相关资源
    最近更新 更多