Assuming the following example array:
{"/documents", "/documents/files", "/pictures"}
I wish to create a multidimensional NSMutableDictionary that looks like (if I were to create it manually):
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);
Which would log as:
documents = {
files = {
};
};
pictures = {
};
How could I generate this automatically from a similar array with path lengths of an infinite length (so dictionaries of infinite dimensions?)
What I have so far (hopefully it’s useful as a starting point) is;
I put the comments of the logic above the code to make it easier on the eyes:
(_folderPaths is the array)
/**
*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);
This would log as:
documents = {
};
files = {
};
pictures = {
};
So I need a way of being able to step deeper into the dictionary with each iteration of the split path. I’ve done this before in C# on a node view where I could reference a child with a cursor but I’m not finding a way to do this with Objective-C using the pointers.
You’re pretty close. All you need to do is dynamically change the parent that new dictionaries get added to. You can do this like this:
Note that under this method, these arrays would all yield the same result: