使用.plist(Cocoa / iPhone SDK)</dict>中的键在数组中创建<dict>

时间:2011-02-28 22:59:13

标签: objective-c cocoa plist nsdictionary add

嘿伙计们,试图以编程方式添加(对象?)给我的plist,这是我到目前为止所做的事情:

 NSString *documentsDirectory = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents/myfolder"]];
        NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"Favourites.plist"];

        NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:writablePath];


        [rootDict setValue:@"My Third PDF" forKey:@"Title"];
        [rootDict writeToFile:writablePath atomically: YES];

并且继承我的plist:

<plist version="1.0">
<dict>
    <key>Rows</key>
    <array>
        <dict>
            <key>SaveName</key>
            <string>first.pdf</string>
            <key>Title</key>
            <string>My first PDF</string>
        </dict>
        <dict>
            <key>SaveName</key>
            <string>second.pdf</string>
            <key>Title</key>
            <string>My Second PDF</string>
        </dict>
    </array>
</dict>
</plist>

如何添加另一个(对象?),如

<dict>
            <key>SaveName</key>
            <string>third.pdf</string>
            <key>Title</key>
            <string>My third PDF</string>
        </dict>

到我的plist?谢谢!

1 个答案:

答案 0 :(得分:2)

你必须确保Rows数组是可变的:

[rootDict setObject:[[rootDict objectForKey:@"Rows"] mutableCopy] forKey:@"Rows"];

您需要创建一个具有该结构的dict,例如

NSDictionary *third = [NDSictionary dictionaryWithObjectsAndKeys:
                       @"third.pdf", @"SaveName",
                       @"My third PDF", @"Title",
                       nil];

并将其添加到数组中:

[[rootDict objectforKey:@"Rows"] addObject:third];