写入plist文件

时间:2012-08-14 14:24:01

标签: iphone plist

我头疼几个小时试图将一些信息写入plist文件。 我的plist看起来像这样:

<plist version="1.0">
<array>
<dict>
    <key>page</key>
    <string>page 1</string>
    <key>description</key>
    <string>description  text 1</string>
</dict>
<dict>
    <key>page</key>
    <string>page 2</string>
    <key>description</key>
    <string>description text 2</string>
</dict>
</array>
</plist>

我只想写一个像plist这样的新条目              页         3         描述         说明文字3     

这是我使用的代码

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,   NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"bookmark.plist"]; //
NSMutableDictionary *rootArray = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
[rootArray setObject:@"Jimmy1" forKey:@"page"];
    [rootArray setObject:@"Jimmy2" forKey:@"description"];
    [rootArray writeToFile:path atomically:YES];

当我运行时,我没有收到任何错误消息但只是写了任何东西到bookmark.plist,你能给我一个关于如何解决这个问题的想法吗?

感谢

2 个答案:

答案 0 :(得分:2)

我相信你的问题是你有一系列的词根而不是根词典。因此,当您初始化NSMutableDictionary时,您实际上正在获取阵列。

我认为您需要初始化NSMutableArray,添加一个新字典作为包含所需对象的对象。然后将你的数组写入文件。

NSMutableArray *rootArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSDictionary *newPage = [NSDictionary dictionaryWithObjectsAndKeys: @"Page 3", @"page", @"Description text 3", @"description"];

[rootArray addObject:newPage];

[rootArray writeToFile:path atomically:YES];

在Xcode中没有检查过这个,但我认为这是你问题的根源。

<强>更新

绝对查看 Rahul 的回答。他记得将write方法包装在if语句中。这绝对是错误处理的最佳实践。

答案 1 :(得分:1)

你的问题是

NSMutableDictionary *rootArray = [[NSMutableDictionary alloc] initWithContentsOfFile:path];` //it will return you array of dict not dictionary

试试这个

 // get your plist file path    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,   NSUserDomainMask, YES); //1
    NSString *documentsDirectory = [paths objectAtIndex:0]; //2
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"bookmark.plist"];

// get content of your plist file     
NSMutableArray *rootArray = [[NSMutableArray alloc] initWithContentsOfFile:path];

// create new dictionary with new content
NSDictionary *newPage = [NSDictionary dictionaryWithObjectsAndKeys: @"Page 3", @"page", @"Description text 3", @"description"];

// add new dictionnay to your rootArray
[rootArray addObject:newPage];

if([rootArray writeToFile:path atomically:YES]) // it will return bool value
{
   NSLog(@"Successfully finished writing to file");
}
else
{
    NSLog(@"failed to write");
}
相关问题