在.h中
#import <Foundation/Foundation.h>
//pdf 基本设置的模型
@interface ScratchPDFSetModel : NSObject<NSCoding>
//颜色
@property (nonatomic, assign) CGFloat R;
@property (nonatomic, assign) CGFloat G;
@property (nonatomic, assign) CGFloat B;
//字体大小
@property (nonatomic, assign) CGFloat font;
@end
在.m中
- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
unsigned int count = 0;
//获取变量名
Ivar *ivars = class_copyIvarList([self class], &count);
for (NSInteger index = 0; index<count; index++) {
Ivar ivar = ivars[index];
const char *name = ivar_getName(ivar);
NSString *strName = [NSString stringWithUTF8String:name];
id value = [self valueForKey:strName];
[aCoder encodeObject:value forKey:strName];
}
free(ivars);
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder {
if (self = [super init]) {
unsigned int count = 0;
// 获取成员的变量名
Ivar *ivars = class_copyIvarList([self class], &count);
for (NSInteger index = 0; index < count; index ++) {
Ivar ivar = ivars[index];
const char * name = ivar_getName(ivar);
NSString *strName = [NSString stringWithUTF8String:name];
id value = [aDecoder decodeObjectForKey:strName];
[self setValue:value forKey:strName];
}
free(ivars);
}
return self;
}
这么做的好处是,不在需要每个属性都实现。如果一个模型的属性多的话,使用runtime的好处就大了。
//这里的attribute 换成你们自己的属性。我这里只是一个说明
- (void)encodeWithCoder:(nonnull NSCoder *)aCoder{
[aCoder encodeObject:self. attribute forKey: @"attribute"];
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder{
if (self = [super init]) {
self. attribute = [aDecoder decodeObjectForKey:@"attribute"];
}
return self;
}
在外部使用:
//归档
ScratchPDFSetModel *model = [ScratchPDFSetModel new];
model.R = 1;
model.G = 0;
model.B = 0;
model.font = 10;
[NSKeyedArchiver archiveRootObject:model toFile:filePath];
//解档
NSString *filePath = [[ScratchPdfTool shareInstance]createPDFSetPlist];
ScratchPDFSetModel *setModel = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];