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

时间:2015-05-21 14:38:26

标签: ios xml swift plist nskeyedarchiver

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

1 个答案:

答案 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)