【发布时间】: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