1

如何获取目录及其所有子文件夹的内容?我想将树存储在NSDictionary.

我希望字典打印如下内容:

{
    MyFolder =     (
        "Water.png",
                {
            MySubfolder =             (
                "Note.txt",
                                {
                    Sub-Subfolder =                     (
                        "3D.pdf",
                        "MyFile.txt"
                    );
                }
            );
        }
    );
}

我试过了:

NSFileManager *manager = [NSFileManager defaultManager];

    NSArray *array = [manager contentsOfDirectoryAtPath:path error:nil];
    NSMutableDictionary *files = [[NSMutableDictionary alloc]init];
            NSString  *newPath = @"";
    for (int i=0; array.count>i; i++) {

        newPath = [NSString stringWithFormat:@"%@/%@", path, [array objectAtIndex:i]];
        //echo(newPath);
        if ([[[manager attributesOfItemAtPath:newPath error:nil] objectForKey:NSFileType] isEqualToString:NSFileTypeRegular])
        {
            NSLog(@"Setting: %@||%@", [array objectAtIndex:i], [newPath lastPathComponent]);

            [files setObject:[array objectAtIndex:i] forKey:[newPath lastPathComponent]];


        }
        else
        {echo([NSString stringWithFormat:@"newPath=%@", newPath]);
            dict = [self reachedDirectory:newPath dict:dict oldPath:path];

        }


    }
    NSMutableDictionary *transferred = [dict objectForKey:[newPath lastPathComponent]];
    if (!transferred) {
        transferred = [[NSMutableDictionary alloc]init];
    }
    for (int n=0; files.count>n; n++) {
        [transferred setObject:[[files allValues] objectAtIndex:n] forKey:[[files allKeys] objectAtIndex:n]];
    }
    echo([newPath lastPathComponent]);
    [dict setObject:transferred forKey:[path lastPathComponent]];
    return dict;

但是所有文件夹都没有对齐,并且没有超过子文件夹的第二个维度。我希望它能够拥有尽可能多的子文​​件夹。

谢谢你的帮助!

4

1 回答 1

1

您可以使用 NSDirectoryEnumerator 类,它提供了 enumerateAtPath 方法,因此您只需传递主文件夹路径并在其中循环您的条件。这样无论您的子文件夹存在什么,它都会相应地打印路径。

于 2013-10-19T19:26:24.170 回答