我正在使用这两种递归方法来查找某个文件夹中文件和目录的路径
- (NSMutableArray *)getFilePathsFromDirectory:(NSString *)directory{
NSMutableArray *contents = [[NSMutableArray alloc] init];
NSArray *arr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directory error:nil];
for (NSString *file in arr) {
BOOL isDir;
[[NSFileManager defaultManager] fileExistsAtPath:[directory stringByAppendingPathComponent:file] isDirectory:&isDir];
if (!isDir) {
[contents addObject:[directory stringByAppendingPathComponent:file]];
}
else{
[contents addObject:[directory stringByAppendingPathComponent:file]];
[contents addObject:[self getFilePathsFromDirectory:[directory stringByAppendingPathComponent:file]]];
}
}
return contents;
}
- (NSString *)getPathForItemNamed:(NSString *)name array:(NSMutableArray *)arr{
NSString *str;
if (name) {
for (NSString *s in arr) {
if ([s isKindOfClass:[NSString class]]) {
if ([[s lastPathComponent] isEqualToString:name]) {
return s;
}
}
}
for (NSMutableArray *aq in arr) {
if ([aq isKindOfClass:[NSMutableArray class]]) {
str = [self getPathForItemNamed:name array:aq];
return str;
}
}
}
return str;
}
但问题是,经过一定数量的子目录(3-5)后,这将停止返回任何路径并返回(null)
. 我觉得这与由于某种原因在返回之前没有填充所有目录的数组有关。这是我如何称呼这些
NSMutableArray *paths = [self getContentsOfPaths:[self downloadsDir]];
path = [self getPathForItemNamed:[tableView cellForRowAtIndexPath:indexPath].textLabel.text array:paths];
NSLog(@"%@", path);