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
我觉得如果我只是不断重复的循环,获取目录的内容,我可能有问题也说不定。
通常你会使用递归或队列来做到这一点。 – Dave 2013-04-10 22:09:45
@Dave我认为递归会是最好的方式,但我不知道如何去做。 – 2013-04-10 22:11:02
这并不难,只需将你的代码放在一个函数中,并且每当它找到一个目录时就使它自己调用一个新的目录进行搜索。队列更好,但递归更直观。 – Dave 2013-04-10 22:12:31