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;

しかし、すべてのフォルダーが整列されておらず、サブフォルダーの 2 番目の次元を超えていません。可能な限り多くのサブフォルダーを持つことができるようにしたいと思います。

ご協力いただきありがとうございます!

4

1 に答える 1

1

NSDirectoryEnumerator クラスを使用できます。これは enumerateAtPath メソッドを提供するため、メイン フォルダー パスを渡すだけで済み、その中で条件をループするだけです。そのため、サブフォルダーが存在する場合は、それに応じてパスが出力されます。

于 2013-10-19T19:26:24.170 に答える