如何将plist保存为带主键的字典? NSDictionary + Plist + Objective C

时间:2014-11-19 17:35:57

标签: objective-c nsdictionary plist

我需要使用主键创建plist字典,例如:@“events”。带键的主字典将调用数据数组。到现在为止,我可以创建plist但是没有主键/字典。这就是我创建plist的方式:

    NSDictionary *eventsDictionary = [dataDictionary objectForKey:@"eventList"];
       NSString *path = [
                              NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject ];
                           path = [path stringByAppendingPathComponent:DATA_DICTIONARY_KEY_USER_DEFAULTS ];
            [[NSDictionary dictionary] writeToFile:path  atomically:YES ];

和我的plist:

我的Plist

<dict>
<key>eventID</key>
<array/>
<string>111</string>
<string>112</string>
<key>eventName</key>
<array>
<string>AAA</string>
<string>BBB</string>
</array>
</dict>

但我希望主词典键为@“Events”:

标题

<dict>
    <key>Events</key>
    <dict>
    <key>eventID</key>
    <array/>
    <string>111</string>
    <string>112</string>
    <key>eventName</key>
    <array>
    <string>AAA</string>
    <string>BBB</string>
    </array>
    </dict>

我的plist只有没有主字典的数据数组,这意味着有一个根和数据数组。

请建议任何解决方案。不幸的是,因为我没有足够的积分所以无法添加任何图像:(

谢谢。

1 个答案:

答案 0 :(得分:0)

听起来您需要将字典放入另一个字典中。类似的东西:

NSDictionary *eventsDictionary = [dataDictionary objectForKey:@"eventList"];
NSDictionary *plistDict = [NSDictionary dictionaryWithObject:eventsDictionary 
                                                      forKey:@"Events"];

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:DATA_DICTIONARY_KEY_USER_DEFAULTS];

[plistDict writeToFile:path atomically:YES];