如何使用 NSKeyedArchiver(或其他机制)以 XML 格式在 plist 中保存自己的 类 列表?

How to save list of own classes in a plist in XML format using NSKeyedArchiver (or other mechanics)?

我设法将二进制格式的 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);
        }
    }
}

假设您的 Bookmark class 采用 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)