1

How would you be able to save a custom object to NSUserDefaults??

NSUserDefaults.standardUserDefaults().setObject(obj, forKey: "object")
NSUserDefaults.standardUserDefaults().synchronize()

The object is of the SPTAuthViewController class in the Spotify iOS SDK, so I can't edit it to add encoder and decoder methods. How can I encode the object into an NSData object to store it in NSUserDefaults?

PoKoBros
  • 701
  • 3
  • 9
  • 25

1 Answers1

0

You can't store custom objects into user defaults. You can only store "property list objects" (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects).

In order to save a custom object to user defaults you have to convert it to one of those types.

You can make your custom object conform to the NSCoding protocol. To do that you have to implement the init(coder:) and encode(coder:) methods. (I believe that's the swift form of the method names - I've been working in Objective-C lately so my Swift is getting rusty.) How you implement those methods depends on your class. Typically you make multiple calls to encodeObject:forKey: to encode your object's properties.

Once your custom object conforms to NSCoding you can convert it to NSData using the NSKeyedArchiver method archivedDataWithRootObject(). You then convert it from NSData back to the original object using the NSKeyedUnarchiver method unarchiveObjectWithData().

EDIT:

I just realized that you were trying to save a view controller object (SPTAuthViewController to user defaults. You should not serialize and save view controller objects. Controller objects should not be used to save application data.

Community
  • 1
  • 1
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • I can't implement the init(coder:) or encode(coder:) methods in my class because the object's class is part of the Spotify SDK. So I can't actually change it. – PoKoBros Apr 16 '16 at 05:40
  • Do you have the source code of the objects from Spotify for reference? Or do they already conform to NSCoding? Or do these classes have existing init methods that let you create and fully configure an object? – Duncan C Apr 16 '16 at 11:09
  • You need to figure out what state data you need to preserve from your `SPTAuthViewController` object, and save that, not your view controller. – Duncan C Apr 16 '16 at 11:12