假設下面的示例陣列:字符串分割到多維的NSMutableDictionary
{"/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中執行此操作的方法。
爲了澄清,更多信息會在每個字典否則我會使用數組。子文件夾將放入包含每個孩子的鍵/對象的字典中。 – amcc 2012-08-15 01:13:56
另一種結構是'Array {FolderDictionary,FolderDictionary,...}',其中每個'folderDictionary'都具有包含相等數組的'name','fullPath'和'childFolders'鍵 - 這可能更簡單並且我試圖啓動用。 – amcc 2012-08-15 01:16:19
但我認爲字典鍵更容易檢查唯一性。我現在會停止評論! – amcc 2012-08-15 01:38:20