将任意NSData写入NSXMLElement的最佳方式 [英] Best way to write arbitrary NSData into an NSXMLElement
问题描述
我允许将应用程序数据(它是10.7上的Mac应用程序)导出为XML文件,并且一个字段我想能够从XML导出/导入为 NSData
字段。什么是正确/接受的方式这样做?我应该转换为base64 并将该字符串写入XML吗?
I am allowing for application data (it's a Mac app on 10.7) to be exported as an XML file, and one field I would like to be able to export/import to/from XML is an NSData
field. What would be the correct/accepted way of doing this? Should I convert to base64 and write that string to XML?
我不想滚动我自己的解决方案,使用类别,作为链接问题的接受答案(链接到 Matt Gallagher的解决方案)。
I would prefer not to roll my own solution, using a category, as the accepted answer to the linked question does (linking to Matt Gallagher's solution).
更新
我刚刚发现了 NSPropertyListSerialization
类。我得到了希望,但它只有静态序列化方法返回 NSData
表示。
推荐答案
我意识到(作为我更新的暗示),我可以使用 -dataWithPropertyList:返回的 NSData
格式:NSPropertyListSerialization_Class / Reference / Reference.htmlrel =nofollow> NSPropertyListSerialization options:error:只是一个UTF-8字符串。这是我用来序列化:
I realized (as my updated alluded to) that I could use the NSPropertyListSerialization class, since the NSData
returned by -dataWithPropertyList:format:options:error:
is just a UTF-8 string. This is what I'm using to serialize:
NSData *data = value;
NSError *error = nil;
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:data
format:NSPropertyListXMLFormat_v1_0
options:0
error:&error];
if (error) {
NSLog(@"Error serializing data to plist XML: %@", error);
} else {
NSString *plistString = [[NSString alloc] initWithData:plistData encoding:NSUTF8StringEncoding];
NSXMLElement *dataElement = [NSXMLElement elementWithName:field
stringValue:plistString];
}
并反序列化:
NSData *plistData = [element.stringValue dataUsingEncoding:NSUTF8StringEncoding];
NSData *originalData = [NSPropertyListSerialization propertyListWithData:plistData
options:NSPropertyListImmutable
format:NULL
error:&error];
if (error) {
NSLog(@"Error deserializing data from plist XML: %@", error);
} else {
value = originalData;
}
这篇关于将任意NSData写入NSXMLElement的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!