contentsOfDirectoryAtPath,包含子文件夹的内容objective-c

时间:2013-10-19 19:18:52

标签: objective-c macos nsarray nsdictionary nsfilemanager

如何获取目录及其所有子文件夹的内容?我想将树存储在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;

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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