【发布时间】:2012-08-15 01:05:12
【问题描述】:
假设以下示例数组:
{"/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 = {
};
如何从具有无限长度的路径长度的类似数组中自动生成它(所以字典是无限维度的?)
到目前为止我所拥有的(希望它作为一个起点有用)是; 我将逻辑的 cmets 放在代码上方,以使其更容易看: (_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 来做到这一点的方法。
【问题讨论】:
-
为了澄清,更多信息将放在每个字典中,否则我会使用数组。子文件夹将放入包含每个子项的键/对象的字典中。
-
另一种结构是
Array { FolderDictionary, FolderDictionary, ...},其中每个folderDictionary都有键name、fullPath和childFolders,其中包含一个相等的数组——这可能更简单,也是我尝试开始的。 -
但我认为字典键更容易检查唯一性。我现在停止评论!
标签: objective-c ios cocoa-touch nsdictionary nsmutabledictionary