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 回答