次の配列例を想定します。
{"/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でこれを実行する方法が見つかりません。