NSUserDefaults storage custom object(NSUserDefaults存储自定义的对象)
Cocoa SDK定义:NSUserDefaults只能存取: NSString, NSNumber, NSData, NSArray, NSDictionary类型数据。
当你需要存取一个NSObject时,那么需要做两步操作。
1,对你的object的属性进行编码和解码
2,在存取时使用NSKeyedArchiver对你的object归档,使用NSKeyedUnArchiver取数据(其原理,把NSObject转化成NSData存入NSUserDefaults中;取出来的时NSData,再转化成NSObject)
详细介绍
1,这里我的object命名为:UserModel,我在.m文件中对属性进行编码,解码操作。
2,存入前需要归档,取出则相反(其原理,把NSObject转化成NSData存入NSUserDefaults中;取出来的时NSData,再转化成NSObject)
注意,在给属性值编码解码时的一个简便方法:
使用方法:在你发送request获取到Json数据(这里前提是NSDictionary,这也是大多数情况下),获取到allKeys,传入值即可打印出所有你想要的代码。
//UserModel code -(void)produceUserCodeWithKeys:(NSArray *)keys{ NSLog(@"\n\n\nUserModel====================================================================UserModel"); NSMutableString *modelContent = [[NSMutableString alloc] init]; [modelContent appendString:@"\n- (void)encodeWithCoder:(NSCoder *)encoder {"]; for (NSString *key in keys) { [modelContent appendString:[NSString stringWithFormat:@"\n [encoder encodeObject:self.%@ forKey:@\"%@\"];",key,key]]; } [modelContent appendString:@"\n}\n\n"]; [modelContent appendString:@"\n- (id)initWithCoder:(NSCoder *)decoder {"]; [modelContent appendString:@"\n if((self = [super init])) {"]; for (NSString *key in keys) { [modelContent appendString:[NSString stringWithFormat:@"\n self.%@ = [decoder decodeObjectForKey:@\"%@\"];",key,key]]; } [modelContent appendString:@"\n }"]; [modelContent appendString:@"\n return self;"]; [modelContent appendString:@"\n}"]; NSLog(@"%@",modelContent); }