Save struct in class to NSUserDefaults using Swift

前端 未结 4 1069
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-30 11:31

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:



        
4条回答
  •  囚心锁ツ
    2020-12-30 12:09

    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.

提交回复
热议问题