1.先创建类目类:继承于NSUserDefaults
2其次前提:保存的model要实现NSCoding
3.在自定义的类目实现这两个方法
-(void)setCustomObj:(id)obj forKey:(NSString *)key;
-(id)customObjForKey:(NSString *)key;
在自定义的类目中实现这两个方法
-(void)setCustomObj:(id)obj forKey:(NSString *)key
{
if ([obj respondsToSelector:@selector(encodeWithCoder:)] == NO) {
NSLog(@"对象存入失败!对象必须实现NSCoding 协议的 encodeWithCoder:方法");
return;
}
NSData * encodeObject = [NSKeyedArchiver archivedDataWithRootObject:obj];
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:encodeObject forKey:key];
[defaults synchronize];
}
-(id)customObjForKey:(NSString *)key
{
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSData * encodeObject = [defaults objectForKey:key];
if (encodeObject == nil) {
return nil;
}
id obj = [NSKeyedUnarchiver unarchiveObjectWithData:encodeObject];
return obj;
}
4.再次来到我们保存model中实现NSCoding协议
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super initWithCoder:decoder];
if (self) {
self.cityId = [decoder decodeObjectForKey:@"cityId"];
self.cityName = [decoder decodeObjectForKey:@"cityName"];
self.cityLat = [decoder decodeObjectForKey:@"cityLat"];
self.cityLng = [decoder decodeObjectForKey:@"cityLng"];
self.firstCharacter = [decoder decodeObjectForKey:@"firstCharacter"];
self.subsidiaryBankId = [decoder decodeObjectForKey:@"subsidiaryBankId"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.cityId forKey:@"cityId"];
[aCoder encodeObject:self.cityName forKey:@"cityName"];
[aCoder encodeObject:self.cityLat forKey:@"cityLat"];
[aCoder encodeObject:self.cityLng forKey:@"cityLng"];
[aCoder encodeObject:self.firstCharacter forKey:@"firstCharacter"];
[aCoder encodeObject:self.subsidiaryBankId forKey:@"subsidiaryBankId"];
}
5.最后来到控制器中,实例化类目,就可以实现保存model