0

次の配列例を想定します。

{"/documents", "/documents/files", "/pictures"}

次のような多次元NSMutableDictionaryを作成したいと思います(手動で作成した場合)。

NSArray *keys = [NSArray arrayWithObjects: @"documents", @"pictures", nil];
NSArray *objects = [NSArray arrayWithObjects: [NSDictionary dictionaryWithObject:[NSDictionary dictionary] forKey:@"files"], [NSDictionary dictionary], nil];

NSMutableDictionary *demoDict = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];

NSLog(@"%@", demoDict);

これは次のようにログに記録されます:

documents = {
    files = {
    };
};
pictures = {
};

パスの長さが無限の類似した配列からこれを自動的に生成するにはどうすればよいですか(つまり、無限の次元の辞書ですか?)

私がこれまでに持っているもの(うまくいけば、それが出発点として役立つことを願っています)は次のとおりです。見やすくするために、コードの上にロジックのコメントを配置しました:(_folderPathsは配列です)

/**
 *set the root dictionary
 *iterate through the array
 *Split the path down by the separator
 *iterate over the path parts
 *make sure there is a part to the part, eliminates initial slash or
    double slashes
 *Check if key exists
 *if not then set a new mutdict for future children with key being the pathpart
**/

NSMutableDictionary *foldersDictionary = [NSMutableDictionary dictionary];


for(NSString *path in _folderPaths){

    NSArray *pathParts = [path componentsSeparatedByString:@"/"];

    for(NSString *pathPart in pathParts){

        if([pathPart length]>0)
        {
            if(![foldersDictionary objectForKey:pathPart])
                [foldersDictionary setObject:[NSMutableDictionary dictionary] forKey:pathPart];
            //Some way to set the new root to reference the Dictionary just created here so it can be easily added to on the next iteration?
        }

    } //end for pathPart in pathParts
} //end for path in _folderPaths

NSLog(@"%@", foldersDictionary);

これは次のようにログに記録されます。

documents = {
};
files = {
};
pictures = {
};

したがって、分割パスを繰り返すたびに、辞書に深く入り込むことができる方法が必要です。以前、カーソルで子を参照できるノードビューのC#でこれを実行しましたが、ポインターを使用してObjective-Cでこれを実行する方法が見つかりません。

4

1 に答える 1

1

あなたはかなり近いです。あなたがする必要があるのは、新しい辞書が追加される親を動的に変更することです。あなたはこのようにこれを行うことができます:

NSMutableDictionary *folders = [NSMutableDictionary dictionary];

for (NSString *path in folderPaths) {
    NSMutableArray *folderStack = [NSMutableArray arrayWithObject:folders];

    for (NSString *component in [path pathComponents]) {
        if ([component isEqualToString:@"/"]) continue;

        NSMutableDictionary *folder = [[folderStack lastObject] objectForKey:component];
        if (folder == nil) {
            folder = [NSMutableDictionary dictionary];
            [[folderStack lastObject] setObject:folder forKey:component];
        }
        [folderStack addObject:folder];
    }
}

この方法では、これらの配列はすべて同じ結果になることに注意してください。

{"/documents", "/documents/pictures", "/documents/pictures/favorites"}
{"/documents/pictures/favorites", "/documents", "/documents/pictures"}
{"/documents/pictures/favorites"}
于 2012-08-15T01:44:31.010 に答える