質問

How can I get the contents of a directory and all of its subfolders? I would like to have tree stored in a NSDictionary.

I want the dictionary to print something like this:

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

Ive tried:

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;

But All of the folders are not aligned and it doesnt go past the second dimension of subfolders. I would like it to be able to have as many subfolders that is possible.

Thanks for your help!

役に立ちましたか?

解決

You can use NSDirectoryEnumerator class and it provides enumerateAtPath method so that you need to just pass your main folder path and inside that just loop your condtion. So that whatever your subfolder exist it will print the path accordingly.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top