Last active
November 19, 2015 03:40
-
-
Save ctrevarthen/86470886ec5aeb1650f3 to your computer and use it in GitHub Desktop.
Saving and loading products with NSUserDefaults
This file contains hidden or 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 ProductManager { | |
| var products : [Product] = [] | |
| var productsKey : String = "products" | |
| let userDefaults = NSUserDefaults.standardUserDefaults() | |
| func saveProductsToDefaults() { | |
| let productsKeyedArchive = NSKeyedArchiver.archivedDataWithRootObject(self.products) | |
| self.userDefaults.setObject(productsKeyedArchive, forKey: productsKey) | |
| } | |
| func loadProductsFromDefaults() { | |
| if let data = self.userDefaults.objectForKey(productsKey) as? NSData { | |
| let unarc = NSKeyedUnarchiver(forReadingWithData: data) | |
| if let savedProducts = unarc.decodeObjectForKey("root") as? [Product] { | |
| self.products = savedProducts | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment