最近写的代码很多,有很多的model,归档,解档的方法写起来很简单,但是很多,不是很方便。所以研究了下用runtime重写归档解档的方法。记录下自己的例子:
自定义super类
@interface Person : NSObject //遵守NSCoding协议
@property (nonatomic,copy) NSString * name;
@property (nonatomic,assign) NSInteger age;
@property (nonatomic,strong) NSArray * datas;
@end
#import "Person.h"
#import <objc/runtime.h> //导入runtime 的框架
@implementation Person
-(void)encodeWithCoder:(NSCoder *)aCoder
{
unsigned int count = 0;
Ivar *ivarList = class_copyIvarList([self class], &count);
for (int i = 0 ; i< count ; i++) {
const char * name = ivar_getName(ivarList[i]);
NSString *key = [NSString stringWithUTF8String:name];
id value = [self valueForKey:key];
[aCoder encodeObject:value forKey:key];
}
free(ivarList); //释放内存
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
unsigned int count = 0;
Ivar *ivarList = class_copyIvarList([self class], &count);
for (int i = 0 ; i< count; i++) {
const char *name = ivar_getName(ivarList[i]);
NSString *key = [NSString stringWithUTF8String:name];
id value = [aDecoder decodeObjectForKey:key];
[self setValue:value forKey:key];
}
free(ivarList); //释放内存
}
return self;
}
@end
//定义一个子类
@interface Stu : Person
/*
*跟super类的属性一样
*/
@property (nonatomic,copy) NSString * name;
@property (nonatomic,assign) NSInteger age;
/*
* 子类自己的属性
*/
@property (nonatomic,assign) float score;
@end-->
<!--## #import "Stu.h"
@implementation Stu
/*
* 因为跟super类的属性相同,所以要写这个,否则会出问题 ,子类独有的属性不用写
*/
@synthesize name;
@synthesize age;
@synthesize datas;
@end
//测试
#import "Stu.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
Person *p1 = [[Person alloc] init];
p1.name = @"小明";
p1.age = 20;
p1.datas = @[@"WO"];
NSData *data1 = [NSKeyedArchiver archivedDataWithRootObject:p1];
Person *p2 = [NSKeyedUnarchiver unarchiveObjectWithData:data1];
NSLog(@"\n p2.name:%@\n p2.age %ld\n p2.datas:%@\n",p2.name,p2.age,p2.datas);
Stu *stu1 = [[Stu alloc] init];
stu1.name = @"xiaofang";
stu1.age = 30;
stu1.datas = @[@"afakl;jhsfajkl"];
stu1.score = 90.0;
NSData *data2 = [NSKeyedArchiver archivedDataWithRootObject:stu1];
Stu *stu2 = [NSKeyedUnarchiver unarchiveObjectWithData:data2];
NSLog(@"\n stu2.name:%@\n stu2.age:%ld\n stu2.datas:%@\n stu2.score: %f",stu2.name,stu2.age,stu2.datas,stu2.score);}
打印的结果如下:
p2.name:小明
p2.age 20
p2.datas:(
WO
)
2018-04-20 14:23:55.968359+0800 TestDemo[4376:188369]
stu2.name:xiaofang //如果声明属性是没有synthesize ,则打印时为null
stu2.age:30
stu2.datas:(
"afakl;jhsfajkl"
)
stu2.score:90.000000