1、归档解档介绍
归档解档是一种常用的轻量型文件存储方式,在项目中,如果需要将数据模型本地化存储,一般就会用到归档和解档。但是如果数据模型中有多个属性的话,我们不得不对每个属性进行处理,这个过程非常繁琐。
这里我们可以参考之前『字典转模型』 的代码。通过 Runtime 获取类的属性列表,实现自动归档和解档。归档操作和解档操作主要会用到了两个方法: encodeObject: forKey:
和 decodeObjectForKey:
。
2、代码实现
首先创建 NSObject 的分类 NSObject+XXModel.h
、NSObject+XXModel.m
,在其中添加以下代码:
// 解档
- (instancetype)xx_modelInitWithCoder:(NSCoder *)aDecoder {
if (!aDecoder) return self;
if (!self) {
return self;
}
unsigned int count;
objc_property_t *propertyList = class_copyPropertyList([self class], &count);
for (unsigned int i = 0; i < count; i++) {
const char *propertyName = property_getName(propertyList[i]);
NSString *name = [NSString stringWithUTF8String:propertyName];
id value = [aDecoder decodeObjectForKey:name];
[self setValue:value forKey:name];
}
free(propertyList);
return self;
}
// 归档
- (void)xx_modelEncodeWithCoder:(NSCoder *)aCoder {
if (!aCoder) return;
if (!self) {
return;
}
unsigned int count;
objc_property_t *propertyList = class_copyPropertyList([self class], &count);
for (unsigned int i = 0; i < count; i++) {
const char *propertyName = property_getName(propertyList[i]);
NSString *name = [NSString stringWithUTF8String:propertyName];
id value = [self valueForKey:name];
[aCoder encodeObject:value forKey:name];
}
free(propertyList);
}
然后在需要实现归档解档的模型中,添加-initWithCoder:
和-encodeWithCoder:
方法。
#import "XXPerson.h"
#import "NSObject+XXModel.h"
@implementation XXPerson
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
[self xx_modelInitWithCoder:aDecoder];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[self xx_modelEncodeWithCoder:aCoder];
}
@end
测试一下归档解档代码:
XXPerson *person = [[XXPerson alloc] init];
person.uid = @"123412341234";
person.name = @"行走少年郎";
person.age = 18;
person.weight = 120;
// 归档
NSString *path = [NSString stringWithFormat:@"%@/person.plist", NSHomeDirectory()];
[NSKeyedArchiver archiveRootObject:person toFile:path];
// 解档
XXPerson *personObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"personObject.uid = %@", personObject.uid);
NSLog(@"personObject.name = %@", personObject.name);
网友评论