Created
January 29, 2018 00:56
-
-
Save KrisYu/11b6027cf03a12022a134cd1f96e6031 to your computer and use it in GitHub Desktop.
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
class Person: NSObject, NSCoding { | |
var firstName: String | |
var lastName: String | |
override var description: String { | |
return self.firstName + " " + self.lastName | |
} | |
init(firstName: String, lastName: String) { | |
self.firstName = firstName | |
self.lastName = lastName | |
super.init() | |
} | |
func encode(with aCoder: NSCoder) { | |
aCoder.encode(self.lastName, forKey: "last") | |
aCoder.encode(self.firstName, forKey: "first") | |
} | |
required init?(coder aDecoder: NSCoder) { | |
self.lastName = aDecoder.decodeObject(forKey: "last") as! String | |
self.firstName = aDecoder.decodeObject(forKey: "first") as! String | |
super.init() | |
} | |
} | |
/// Save to file | |
let moi = Person(firstName: "Matt", lastName: "Neuburg") | |
if let moifile = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("moi.txt"){ | |
do { | |
let moidata = NSKeyedArchiver.archivedData(withRootObject: moi) | |
try moidata.write(to: moifile) | |
print(moifile) | |
print("saved data successfully") | |
} catch let error { | |
print("couldn't save \(error)") | |
} | |
} | |
/// Read from file | |
if let moifile = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("moi.txt"){ | |
do { | |
let persondata = try Data(contentsOf: moifile) | |
let person = NSKeyedUnarchiver.unarchiveObject(with: persondata) as! Person | |
print(person) | |
} catch let error { | |
print("couldn't save \(error)") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment