Attempt to insert non-property value Objective C

天涯浪子 提交于 2019-12-02 16:20:53

If you don't want to bother about ensuring all your dictionary values are the property list types, then you can simply convert the dictionary into NSData,

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
[def setObject:[NSKeyedArchiver archivedDataWithRootObject:self.myDictionary] forKey:@"MyData"];
[def synchronize];

And to get back into a dictionary from sandbox:

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSData *data = [def objectForKey:@"MyData"];
NSDictionary *retrievedDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
self.myDictionary = [[NSDictionary alloc] initWithDictionary:retrievedDictionary];

Hope this helps someone. :D


ADDITIONAL NOTE: If you are getting a mutable dictionary, or mutable array, then remember to use "mutableCopy" method. Otherwise you can't add or delete objects from your retrieved dictionary/array. For example:

NSMutableDictionary *retrievedDictionary = 
[[NSKeyedUnarchiver unarchiveObjectWithData:data] mutableCopy];

Or

NSMutableArray *retrievedArray = 
[[NSKeyedUnarchiver unarchiveObjectWithData:data] mutableCopy];

You can only store property list types (array, data, string, number, date, dictionary) or urls in NSUserDefaults. You'll need to convert your model object to those.

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