Skip to content

Instantly share code, notes, and snippets.

@vorlando
Last active March 8, 2016 12:18
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 vorlando/dc29ba98c93eaadbc7b1 to your computer and use it in GitHub Desktop.
Save vorlando/dc29ba98c93eaadbc7b1 to your computer and use it in GitHub Desktop.
Swift NSCoding Archiving and Unarchiving
import Foundation
class Foo: NSObject, NSCoding {
let identifier:String
init(identifier:String) {
self.identifier = identifier
}
override var description:String {
return "Foo: \(identifier)"
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(identifier, forKey: "identifier")
}
required convenience init?(coder aDecoder: NSCoder) {
guard let identifier = aDecoder.decodeObjectForKey("identifier") as? String
else {
return nil
}
self.init(identifier:identifier)
}
}
class Bar:Foo {
let tag:String
init(identifier:String, tag:String) {
self.tag = tag
super.init(identifier: identifier)
}
override func encodeWithCoder(aCoder: NSCoder) {
super.encodeWithCoder(aCoder)
aCoder.encodeObject(tag, forKey: "tag")
}
required convenience init?(coder aDecoder: NSCoder) {
guard let
identifier = aDecoder.decodeObjectForKey("identifier") as? String,
tag = aDecoder.decodeObjectForKey("tag") as? String else {
return nil
}
self.init(identifier:identifier, tag:tag)
}
override var description:String {
return "Bar: \(identifier) is \(tag)"
}
}
let b = Bar(identifier: "name", tag: "red")
NSKeyedArchiver.archiveRootObject(b, toFile: "archive")
let _b = NSKeyedUnarchiver.unarchiveObjectWithFile("archive")!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment