我设法将二进制格式的plist写入磁盘。 但我无法以XML格式编写数据。我读过这应该是可能的,但没有示例代码或文档这样做。
存储的代码有效:
var listofbookmarks = [Bookmark]() // <- needed to create a mutable array instance
listofbookmarks.append(Bookmark(name: "myname", position: "100"))
let fileManager = NSFileManager.defaultManager()
if let directories = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
if !directories.isEmpty {
let plistpath = directories[0].stringByAppendingPathComponent("BookmarkArray.plist")
if !fileManager.fileExistsAtPath(plistpath) {
// HOWTO TO STORE IN XML ?
NSKeyedArchiver.archiveRootObject(listofbookmarks, toFile: plistpath)
println(plistpath);
}
}
}
答案 0 :(得分:2)
假设您的Bookmark类正在采用NSCoding协议,您只需将NSKeyedArchiver outputFormat
设置为NSPropertyListFormat.XMLFormat_v1_0
:
替换
NSKeyedArchiver.archiveRootObject(listofbookmarks, toFile: plistpath)
与
let archivedData = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: archivedData)
archiver.outputFormat = NSPropertyListFormat.XMLFormat_v1_0
archiver.encodeObject(listofbookmarks)
archiver.finishEncoding()
archivedData.writeToFile(plistpath, atomically: true)