Saving cell accessory to NSUserDefaults

霸气de小男生 提交于 2019-12-11 22:55:25

问题


I've previously asked a question which was answered here regarding saving the state of of a cell accessory. I'm now playing with NSUserDefaults. I've successfully saved a number of options in my app but can't seem to save the state of the cell accessory to NSUserDefaults.

After a number of tries, I've come to the conclusion I don't know what or where to save as well as where to recall the saved options.

Can anyoone point me in the right direction?

Thanks,

EDIT: Whilst I understand the variable will likely need to be converted, I'm having a hard time what needs to be converted and when.


回答1:


In the question that you cite the code snippets use an instance variable named _accessoryStyle. The variable has the type NSMutableArray. Assuming that you still have this variable, you can simply save its content to the user defaults like this:

NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:self._accessoryStyle forKey:@"aKeyName"];

If you later want to retrieve the data, you can do it like this:

NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
NSArray* immutableData = [userDefaults arrayForKey:@"aKeyName"]];
[self._accessoryStyle setArray:immutableData];

Retrieving is slightly more complicated because arrayForKey: returns an immutable NSArray, not an NSMutableArray.




回答2:


For objects that aren't NSData, NSDate, NSString, NSArray, NSDictionary, NSNumber (since they can't be saved on a plist file), you could use these macros:

#define SetDefaultObjectForKey(object, key) [ [NSUserDefaults standardUserDefaults] setObject: [NSKeyedArchiver archivedDataWithRootObject: object] forKey: key]

#define GetDefaultObjectForkey(key) [NSKeyedUnarchiver unarchivedObjectWithData: [ [NSUserDefaults standardUserDefaults] objectForKey: key] ]

So you are converting them to NSData when saving, and decoding them from NSData to their original type when reading, provided that the object implements the NSCoding protocol. If not so, you should provide an implementation.



来源:https://stackoverflow.com/questions/14184397/saving-cell-accessory-to-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!