【问题标题】:Using NSKeyedArchiver to generate XML from NSManagedObjects held in an NSDictionary使用 NSKeyedArchiver 从 NSDictionary 中保存的 NSManagedObjects 生成 XML
【发布时间】:2011-10-04 15:41:27
【问题描述】:
我有一个 NSDictionary,其中包含一堆 NSManagedObjects。
然后我可以使用 NSKeyedArchiver 将其写入 NSData 对象。
这些是使用this method. 生成的,它工作正常,允许我将一部分模式保存到磁盘,然后将其作为核心数据模型中的一组新对象读回。
如果我使用任一archivedDataWithRootObject:
或archiveRootObject:toFile:,根据documentation
我可以看到存档的格式是 NSPropertyListBinaryFormat_v1_0,而我想在 NSPropertyListXMLFormat_v1_0 中序列化,这样我就可以将我的对象写入一个文件,然后在其他地方将它们作为普通的旧 XML 处理。 (实际上我想在基于 Windows 的系统上从它们生成文档。)
1) 有没有办法可以做到这一点?如果有怎么办?
2) 有没有更好的方法。
我想保持序列化性质,因为我还想稍后将文件发送回 iOS 设备并重新创建对象模型。
【问题讨论】:
标签:
ios
cocoa
core-data
nskeyedarchiver
【解决方案1】:
- 使用
initForWritingWithMutableData: 创建您自己的NSKeyedArchiver 实例。
- 用
setOutputFormat:NSPropertyListXMLFormat_v1_0设置格式。
- 使用
encodeObject:forKey: 编码您的根对象。
- 致电
finishEncoding。
要取消归档您以这种方式编码的数据,您必须同样实例化 NSKeyedUnarchiver。
【解决方案2】:
感谢奥莱!我正朝着那个方向前进,但不确定这是否正确。这是我在代码中所做的,以防它对某人有所帮助。
NSDictionary *dataAsDictionary=[self toDictionaryBlockingRelationships:blockRelationship];
NSString *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
NSMutableData *xmlData=[NSMutableData data];
NSKeyedArchiver *archive=[[NSKeyedArchiver alloc ]initForWritingWithMutableData:xmlData];
[archive setOutputFormat:NSPropertyListXMLFormat_v1_0];
[archive encodeRootObject:dataAsDictionary];
[archive finishEncoding];
if(![xmlData writeToFile:savePath atomically:NO]){
NSLog(@"Failed to write to file to filePath=%@", savePath);
}
[archive release];