NSUserDefaults does not support all objects, such as NSString , NSDictionary and most importantly, NSData . It uses the NSCoding protocol. This allows us to convert custom objects into chunks of NSData . To do this, use the NSKeyedArchiver class to turn a custom object corresponding to NSCoding into an equivalent NSData
let obj = User() let data = NSKeyedArchiver. archivedDataWithRootObject(obj)
Documents can be found here and the method you are looking for is
class func archivedDataWithRootObject(_ rootObject: AnyObject) -> NSData
To retrieve information from NSUserDefaults , use the "reverse" class, NSKeyedUnarchiver . His suitable method is as follows
class func unarchiveObjectWithData(_ data: NSData) -> AnyObject?
Here is an example.
let data = NSUserDefaults.standardUserDefaults().objectForKey("somekey") let obj = NSKeyedUnarchiver. unarchiveObjectWithData(data) as User?
Note. I may have mixed up some additional options, but you get a jist. The documentation for NSKeyedUnarchiver can be found here .
Edit: Fixing a problem with OP was as simple as using NSKeyedArchiver and a subclass of NSObject .
source share