Skip to content

Instantly share code, notes, and snippets.

@kechan
Last active September 27, 2017 20:38
Show Gist options
  • Save kechan/9cfd27442399edfc4773ea639a4c3373 to your computer and use it in GitHub Desktop.
Save kechan/9cfd27442399edfc4773ea639a4c3373 to your computer and use it in GitHub Desktop.
NSCoding Archiving with Playground
let docsDir = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
print(docsDir)
let archiveURL = docsDir.appendingPathComponent("landmark")
print(archiveURL.path)
class LandmarkClass : NSObject, NSCoding {
var name = ""
init(name: String) {
self.name = name
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
}
required convenience init?(coder aDecoder: NSCoder) {
if let name = aDecoder.decodeObject(forKey: "name") as? String {
self.init(name: name)
} else {
return nil
}
}
}
let myLandmarkClass = LandmarkClass(name: "World Trade Center")
NSKeyedArchiver.archiveRootObject(myLandmarkClass, toFile: archiveURL.path)
if let me = NSKeyedUnarchiver.unarchiveObject(withFile: archiveURL.path) as? LandmarkClass {
print(me.name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment