iOS - 如何读取和写入此格式的plist

时间:2012-10-01 21:26:50

标签: iphone ios plist

我有以下格式的xml -

<plist version="1.0">
<array>
    <dict>...</dict>
    <dict>...</dict>
</array>
</plist>

我正在尝试使用 -

将其写入plist
NSDictionary *temp = [NSPropertyListSerialization propertyListWithData:returnData options:NSPropertyListImmutable format:&format error:&errorDesc];
[self writeToPlistFile:@"myList.plist" : temp];

方法

-(BOOL)writeToPlistFile:(NSString*)filename:(NSDictionary*)data{
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * path = [documentsDirectory stringByAppendingPathComponent:filename];
BOOL didWriteSuccessfull = [data writeToFile:path atomically:YES];
return didWriteSuccessfull;
}

然后我想阅读它并将其放入字典中。我该怎么做?

3 个答案:

答案 0 :(得分:2)

如果plist以<array>标记

开头,请使用此选项

NSMutableArray* documentArray = [NSMutableArray arrayWithContentsOfFile:sourcePath];

其中sourcePath是plist的路径。

答案 1 :(得分:0)

使用以下替换filePath,使用与保存它相同的路径。

NSDictionary *yourDictionary = [NSDictionary dictionaryWithContentsOfFile:filePath];

答案 2 :(得分:0)

-(void)saveData:(NSString*)data
{
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentDirectory=[paths objectAtIndex:0];
        NSString *fileName=[NSString stringWithFormat:@"%@/%d.txt",documentDirectory,1];
        NSString *content=data;
        NSFileHandle *fileHandler= [NSFileHandle fileHandleForWritingAtPath:fileName];
        [fileHandler seekToEndOfFile];
        [fileHandler writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
        [fileHandler closeFile];
        NSLog(@"%@",fileName);
}