Skip to content

Instantly share code, notes, and snippets.

@KrisYu
Created January 29, 2018 02:38
Show Gist options
  • Save KrisYu/21c3e3240cca34bcfa9678b9b6945d02 to your computer and use it in GitHub Desktop.
Save KrisYu/21c3e3240cca34bcfa9678b9b6945d02 to your computer and use it in GitHub Desktop.
class Person: NSObject, Codable {
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()
}
}
/// 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 = try PropertyListEncoder().encode(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 = try PropertyListDecoder().decode(Person.self, from: persondata)
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