Skip to content

Instantly share code, notes, and snippets.

@nyg
Created August 29, 2017 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyg/8104d52292af99e69935bf3cbd78469d to your computer and use it in GitHub Desktop.
Save nyg/8104d52292af99e69935bf3cbd78469d to your computer and use it in GitHub Desktop.
Serialize NSObject (or array of) to XML in Swift.
import Foundation
class MyClass: NSObject, NSCoding {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
// MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(age, forKey: "age")
}
required convenience init?(coder aDecoder: NSCoder) {
guard let name = aDecoder.decodeObject(forKey: "name") as? String
else { return nil }
let age = aDecoder.decodeInteger(forKey: "age")
self.init(name: name, age: age)
}
}
/* With an object */
let o = MyClass(name: "me", age: 42)
let coderO = NSKeyedArchiver()
coderO.outputFormat = .xml
coderO.encode(o)
let decoderO = NSKeyedUnarchiver(forReadingWith: coderO.encodedData)
print(String(data: coderO.encodedData, encoding: .utf8)!)
if let decoded = decoderO.decodeObject() as? MyClass {
print(decoded.name)
}
/* With an array */
let a = [ MyClass(name: "me", age: 42), MyClass(name: "you", age: 21) ]
let coderA = NSKeyedArchiver()
coderA.outputFormat = .xml
coderA.encode(a)
let decoderA = NSKeyedUnarchiver(forReadingWith: coderA.encodedData)
print(String(data: coderA.encodedData, encoding: .utf8)!)
if let decoded = decoderA.decodeObject() as? [MyClass] {
decoded.forEach { print($0.name) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment