2013-04-10 46 views
0

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

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 

我觉得如果我只是不断重复的循环,获取目录的内容,我可能有问题也说不定。

+0

通常你会使用递归或队列来做到这一点。 – Dave 2013-04-10 22:09:45

+0

@Dave我认为递归会是最好的方式,但我不知道如何去做。 – 2013-04-10 22:11:02

+0

这并不难,只需将你的代码放在一个函数中,并且每当它找到一个目录时就使它自己调用一个新的目录进行搜索。队列更好,但递归更直观。 – Dave 2013-04-10 22:12:31

回答

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) 
+0

这是我最终做的,谢谢。 – 2013-04-10 22:24:10