归档与解档是IOS中一种序列化与反序列化的方式。对象要实现序列化需要遵循NSCoding协议,而绝大多数Foundation和Cocoa Touch类都遵循了NSCoding协议。下面看看具体的实现方式:
一、在需要归档的类中遵循归档协议:
@interface Person : NSObject<NSCoding>
//需要归档的属性
@property (nonatomic, strong)NSString *name;
@property (nonatomic, assign)NSInteger age;
@end
二、在归档对象的.m方法中实现NSCoding的协议方法
方法一:普通方式实现:
- (void)encodeWithCoder:(NSCoder *)coder
{
//告诉系统归档的属性是哪些
[coder encodeObject:self.name forKey:@"name"];
[coder encodeInteger:self.age forKey:@"age"];
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
//解档
self.name = [coder decodeObjectForKey:@"name"];
self.age = [coder decodeIntegerForKey:@"age"];
}
return self;
}
方法二:使用runtime方法实现:
- (void)encodeWithCoder:(NSCoder *)coder
{
//告诉系统归档的属性是哪些
unsigned int count = 0;//表示对象的属性个数
Ivar *ivars = class_copyIvarList([Person class], &count);
for (int i = 0; i<count; i++) {
//拿到Ivar
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);//获取到属性的C字符串名称
NSString *key = [NSString stringWithUTF8String:name];//转成对应的OC名称
//归档 -- 利用KVC
[coder encodeObject:[self valueForKey:key] forKey:key];
}
free(ivars);//在OC中使用了Copy、Creat、New类型的函数,需要释放指针!!(注:ARC管不了C函数)
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
//解档
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([Person class], &count);
for (int i = 0; i<count; i++) {
//拿到Ivar
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
NSString *key = [NSString stringWithUTF8String:name];
//解档
id value = [coder decodeObjectForKey:key];
// 利用KVC赋值
[self setValue:value forKey:key];
}
free(ivars);
}
return self;
}
注:使用runtime的好处不言而喻,无论对象有多少属性都可以通过这个for循环搞定,非常棒。
三、在Controller中实现具体的存取操作
- (IBAction)save:(UIButton *)sender {
Person *person = [[Person alloc] init];
person.name = @"Frank";
person.age = 18;
//这里以temp路径为例,存到temp路径下
NSString *temp = NSTemporaryDirectory();
NSString *filePath = [temp stringByAppendingPathComponent:@"obj.data"]; //注:保存文件的扩展名可以任意取,不影响。
NSLog(@"%@", filePath);
//归档
[NSKeyedArchiver archiveRootObject:person toFile:filePath];
}
- (IBAction)read:(UIButton *)sender {
//取出归档的文件再解档
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"obj.data"];
//解档
Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"name = %@, age = %ld",person.name,person.age);
}
控制台输出:
name = Frank, age = 18