首先创建model,这里先就叫UserModel
@interface UserModel : NSObject<NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *nickName;
@property (nonatomic, copy) NSString *realName;
@property (nonatomic, copy) NSString *birthday;
@property (nonatomic, copy) NSString *email;
@property (nonatomic, copy) NSString *cerNumber;
@property (nonatomic, copy) NSString *phoneNumber;
@end
#import "UserModel.h"
@implementation UserModel
//必须实现的代理方法
- (void)encodeWithCoder:(NSCoder *)encoder
{
unsigned int count = 0;
// 利用runtime获取实例变量的列表
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i ++) {
// 取出i位置对应的实例变量
Ivar ivar = ivars[i];
// 查看实例变量的名字
const char *name = ivar_getName(ivar);
// C语言字符串转化为NSString
NSString *nameStr = [NSString stringWithCString:nameencoding:NSUTF8StringEncoding];
// 利用KVC取出属性对应的值
id value = [self valueForKey:nameStr];
// 归档
[encoder encodeObject:value forKey:nameStr];
}
// 记住C语言中copy出来的要进行释放
free(ivars);
}
- (id)initWithCoder:(NSCoder *)decoder
{
if (self = [super init]) {
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i ++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
//
NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
id value = [decoder decodeObjectForKey:key];
// 设置到成员变量身上
[self setValue:value forKey:key];
}
free(ivars);
}
return self;
}
接下来在Controller中 将UserModel归档,在需要的地方解归档:
UserModel *model = [[UserModel alloc] init];
model.name = @"姓名";
model.nickName = @"凉凉";
model.realName = @"真实姓名";
model. birthday = @"1998.10.18";
model. email = @"1567345678@qq.com";
model. cerNumber = @"5678886625262";
model. phoneNumber = @"16782828823";
//先把model归档
1. NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:model];
2.[userdefaults setObject:homeData forKey:@“ model“];
3.在需要的地方解归档
NSData *getData = [userdefaults objectForKey:@“homeModel”];
homeModel = [NSKeyedUnarchiver unarchiveObjectWithData:getData];