Last active
March 8, 2016 12:18
-
-
Save vorlando/dc29ba98c93eaadbc7b1 to your computer and use it in GitHub Desktop.
Swift NSCoding Archiving and Unarchiving
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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