注意,实现NSCoding协议不能使用extension,因为指定构造器不能声明在extension中
#import <Foundation/Foundation.h>
//实现NSCoding协议
@interface RTAutoArchive : NSObject<NSCoding>
@end
#import "RTAutoArchive.h"
#import <objc/runtime.h>
@implementation RTAutoArchive
- (void)encodeWithCoder:(NSCoder *)encoder
{
unsigned int count = 0;
//实例变量的列表
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);
//转化为NSString
NSString *nameStr = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
//利用KVC取出属性对应的值
id value = [self valueForKey:nameStr];
//归档
[encoder encodeObject:value forKey:nameStr];
}
//释放
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;
}
@end