Last active
September 27, 2017 20:38
-
-
Save kechan/9cfd27442399edfc4773ea639a4c3373 to your computer and use it in GitHub Desktop.
NSCoding Archiving with Playground
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
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