持久化 轻量数据

今天在使用NSUserDefault的时候报错Attempt to insert non-property value .... of class。

原因是:我存储的是自定义对象,而NSUserDefault只支持部分内置对象的存储。

解决办法:

Here is one example per request:



Save:



NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSMutableArray *arr = ... ; // set value

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr];

[defaults setObject:data forKey:@"theKey"];


Load: NSUserDefaults
*defaults = [NSUserDefaults standardUserDefaults]; NSData *data = [defaults objectForKey:@"theKey"]; NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data]; The element in the array implements @interface CommentItem : NSObject<NSCoding> { NSString *value; } Then in the implementation of CommentItem, provides two methods: -(void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:value forKey:@"Value"]; } -(id)initWithCoder:(NSCoder *)decoder { self.value = [decoder decodeObjectForKey:@"Value"]; return self; }

你可能感兴趣的:(持久化)