NSMutableDictionary添加子

时间:2014-05-11 01:03:47

标签: objective-c cocoa nsdictionary nsmutabledictionary

关于如何使用NSMutableDictionary并使其成为另一个我无法理解的NSMutableDictionary的孩子,必定会有一些缺失的关键元素。我已经尝试了所有的东西,我开始认为跳下桥可能会解决问题。

电流:

DICT:1 root
          |_main dict

DICT:2 root
          |_dict [A]
               |
               sub dict...

所需:

DICT:1 root
         |_main dict
                   |_dict [A]
                        |
                        sub dict....

任何时候我尝试将“DICT:2”添加到“DICT:1”时它会覆盖主要词典。离开我:

DICT:1 root
          |_dict [A]
               |
               sub dict...

我尝试了很多东西,包括:

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];

[myDict setObject:@"mainDict" forKey:@"mainDict"];
[myDict setObject:@"dictA" forKey:@"mainDict"];

也尝试过:

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];

[myDict addEntriesFromDictionary:dictA];

NSMutableDictionary *moarDict = [myDict objectForKey:@"mainDict"];
[moarDict addEntriesFromDictionary:dictA];

和:

moarDict = [dictA mutableCopy];

啊! NSMutableDictionary必须恨我,因为毫无疑问我讨厌它。

1 个答案:

答案 0 :(得分:1)

试试这个:

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *mainDict = [[NSMutableDictionary alloc] init];
[myDict setObject:mainDict forKey:@"mainDict"];
[myDict[@"mainDict"] setObject:dictA" forKey:@"dictA"];

这导致

myDict
    | mainDict
            | dictA
                 | sub dict