新建NSObject分类NSObject+Encode
在分类中重写NSObject的编码反编码方法
- (void)encodeWithCoder:(NSCoder *)aCoder;
- -(instancetype)initWithCoder:(NSCoder *)aDecoder;
在NSObject+Encode.m中 引入 #import <objc/runtime.h>
代码如下:
#import "NSObject+Encode.h"
#import <objc/runtime.h>
@implementation NSObject (Encode)
- (void)encodeWithCoder:(NSCoder *)aCoder{
// 得到实例变量链表
// 创建ivarCount保存实例变量个数
unsigned int ivarCount = 0;
Ivar *vars = class_copyIvarList([self class], &ivarCount);
// 循环遍历实例变量链表
for (int i = 0; i < ivarCount; i++) {
// 获得实例变量名
NSString *varName = [NSString stringWithUTF8String:ivar_getName(vars[i])];
// 通过KVC获取实例变量的值
id value = [self valueForKey:varName];
// 对此值,以实例变量名作为key进行归档
[aCoder encodeObject:value forKey:varName];
}
free(vars);
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
// 初始化方法
self = [self init];
if (self) {
// 获取实例变量链表
unsigned int ivarCount = 0;
Ivar *vars = class_copyIvarList([self class], &ivarCount);
// 循环遍历实例变量链表
for (int i = 0; i < ivarCount; i++) {
// 获得实例变量名
NSString *varName = [NSString stringWithUTF8String:ivar_getName(vars[i])];
// 以实例变量名为key进行反归档
id value = [aDecoder decodeObjectForKey:varName];
// 通过KVC对此对象的实例变量进行赋值
[self setValue:value forKey:varName];
}
free(vars);
}
return self;
}
@end
新建Student类声明两个属性
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign) NSInteger age;
对Student进行归档反归档
Student *stu = [[Student alloc]init];
stu.name = @"zhang";
stu.age = 26;
// 进行归档
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:stu];
// 进行反归档
Student *stu2 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"stu:%@,%ld",stu.name,stu.age);
NSLog(@"stu2:%@,%ld",stu2.name,stu2.age);
NSLog(@"=======");
stu.name = @"李四";
stu.age = 100;
NSLog(@"stu:%@,%ld",stu.name,stu.age);
NSLog(@"stu2:%@,%ld",stu2.name,stu2.age);
运行结果:
网友评论