Search code examples
iosxmlswiftplistnskeyedarchiver

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


I manage to write a plist in binary format to disk. But I do not manage to write the data in XML format. I read this should be possible, but there is no sample code or documentation doing this.

Code for storing which works:

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);
        }
    }
}

Solution

  • Assuming your Bookmark class is adopting the NSCoding protocol, all you have to do is set your NSKeyedArchiver outputFormat to NSPropertyListFormat.XMLFormat_v1_0:

    Replace

    NSKeyedArchiver.archiveRootObject(listofbookmarks, toFile: plistpath)
    

    with

    let archivedData = NSMutableData()
    let archiver = NSKeyedArchiver(forWritingWithMutableData: archivedData)
    archiver.outputFormat = NSPropertyListFormat.XMLFormat_v1_0
    archiver.encodeObject(listofbookmarks)
    archiver.finishEncoding()
    archivedData.writeToFile(plistpath, atomically: true)