In a previous post I showed how to persist single values. This post shows how to save objects/classes of data.
You app needs to take data from memory and store it in a file. This is what the NSKeyedArchiver does. It "archives" the data or writes it for future use.
To restore the archived data (file) back into memory you use the NSKeyedUnarchiver. This will restore your data back into a class you can then use in your code.
(Swift 3)
class SaveClassToUserDefaultsVC: UIViewController { @IBOutlet weak var NameTextField: UITextField! @IBOutlet weak var AgeTextField: UITextField! let defaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() GetPerson() } @IBAction func SavePerson(sender: AnyObject) { let person = Person(name: NameTextField.text!, age: AgeTextField.text!) let personData = NSKeyedArchiver.archivedData(withRootObject: person) defaults.set(personData, forKey: "personData") } func GetPerson() { if let personData = defaults.data(forKey: "personData") { if let person = NSKeyedUnarchiver.unarchiveObject(with: personData) as? Person { NameTextField.text = person.name AgeTextField.text = person.age } } } }
What is NSKeyedArchiver and NSKeyedUnarchiver?
If you are familiar with other languages this is similar to serializing and deserializing.You app needs to take data from memory and store it in a file. This is what the NSKeyedArchiver does. It "archives" the data or writes it for future use.
To restore the archived data (file) back into memory you use the NSKeyedUnarchiver. This will restore your data back into a class you can then use in your code.
Setup You Class To Be "Archivable"
There is some setup work you have to do to your class before it can be archived and unarchived.class Person: NSObject, NSCoding { var name = "" var age = "" required init(name: String, age: String) { self.name = name self.age = age } required init(coder decoder: NSCoder) { self.name = decoder.decodeObject(forKey: "name") as? String ?? "" self.age = decoder.decodeObject(forKey: "age") as? String ?? "" } func encode(with coder: NSCoder) { coder.encode(self.name, forKey: "name") coder.encode(self.age, forKey: "age") } }
(Swift 3)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.