假设以下示例数组:
{"/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 来做到这一点。