I have a class and inside the class is a (swift) array, based on a global struct. I want to save an array with this class to NSUserDefaults. This is my code:
NSUserDefaults
is limited in the types it can handle: NSData
, NSString
, NSNumber
, NSDate
, NSArray
, NSDictionary
, and Bool
. Thus no Swift objects or structs can be saved. Anything else must be converted to an NSData
object.
NSUserDefaults
does not work the same way as NSArchiver
. Since you already have added NSCoder
to your classes your best choice might be to save and restore with NSArchiver
to a file in the Documents
directory..
From the Apple NSUserDefaults
Docs:
A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData.