Created
February 4, 2015 19:40
-
-
Save benaneesh/8d19a70ff6469fff7489 to your computer and use it in GitHub Desktop.
Getting NSCoding on swift
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
import UIKit | |
class ClassName: NSObject, NSCoding { | |
var myVariable: String? | |
override init() {} | |
required init(coder aDecoder: NSCoder) { | |
myVariable = aDecoder.decodeObjectForKey("myVariable") as? String | |
} | |
func encodeWithCoder(aCoder: NSCoder) { | |
if let theVariable = myVariable { | |
aCoder.encodeObject(theVariable, forKey: "myVariable") | |
} | |
} | |
func save() { | |
let data = NSKeyedArchiver.archivedDataWithRootObject(self) | |
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "ClassName") | |
} | |
func clear() { | |
NSUserDefaults.standardUserDefaults().removeObjectForKey("ClassName") | |
} | |
class func loadSaved() -> ClassName? { | |
if let data = NSUserDefaults.standardUserDefaults().objectForKey("ClassName") as? NSData { | |
return NSKeyedUnarchiver.unarchiveObjectWithData(data) as? ClassName | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment