想要将User直接一个Model保存在NSUserDefault
保存如下
User *user = [User new];
NSDictionary *userDic = resultDic[@"user"];
[user setValuesForKeysWithDictionary: userDic];
[SaveObject saveModel:user WithKey:@"user"];
SaveObject.h
/**
* 保存对象
*/
+ (void)saveModel:(id)model WithKey:(NSString *)key;
/**
* 获取对象
*/
+ (id)getModelWithKey:(NSString *)key;
SaveObject.m
// 保存对象
+ (void)saveModel:(id)model WithKey:(NSString *)key{
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:model forKey:key];
[archiver finishEncoding];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:key];
}
// 获取对象
+ (id)getModelWithKey:(NSString *)key{
NSData *deData = [[NSUserDefaults standardUserDefaults] objectForKey:key];
NSKeyedUnarchiver *uKey = [[NSKeyedUnarchiver alloc] initForReadingWithData:deData];
id model = [uKey decodeObjectForKey:key];
return model;
}
但是这个时候会在这里出现这样的错误。
划重点:归档自定义的对象 遵守NSCoding协议
添加 NSObject -> Category 命名:NSObject+FollowCoding
NSObject+FollowCoding.h 中 遵循 <NSCoding>
@interface NSObject (FollowCoding)<NSCoding>
NSObject+FollowCoding.m
- (void)encodeWithCoder:(NSCoder *)aCoder{
unsigned int propertyCount = 0;
objc_property_t *propertys = class_copyPropertyList([self class], &propertyCount);
for (int i = 0; i < propertyCount; i++) {
objc_property_t property = propertys[i];
const char * key = property_getName(property);
id value = [self valueForKey:[NSString stringWithUTF8String:key]];
NSString *attr = [NSString stringWithUTF8String:property_getAttributes(property)];
if ([attr componentsSeparatedByString:@","].count == 3) {
[aCoder encodeInteger:[value integerValue] forKey:[NSString stringWithUTF8String:key]];
} else{
[aCoder encodeObject:value forKey:[NSString stringWithUTF8String:key]];
}
}
free(propertys);
}
#pragma clang diagnostic ignored "-Wobjc-designated-initializers"
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
unsigned int propertyCount = 0;
objc_property_t *propertys = class_copyPropertyList([self class], &propertyCount);
for (int i = 0; i < propertyCount; i++) {
objc_property_t property = propertys[i];
const char * key = property_getName(property);
NSString *attr = [NSString stringWithUTF8String:property_getAttributes(property)];
if ([attr componentsSeparatedByString:@","].count == 3) {
[self setValue:@([aDecoder decodeIntegerForKey:[NSString stringWithUTF8String:key]]) forKey:[NSString stringWithUTF8String:key]];
} else{
[self setValue:[aDecoder decodeObjectForKey:[NSString stringWithUTF8String:key]] forKey:[NSString stringWithUTF8String:key]];
}
}
free(propertys);
return self;
}