归档解档--runtime
不说废话,直接上代码。
首先创建一个Person类。
Person.h
import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding> //遵循NSCoding协议
//创建几个属性
@property (nonatomic, strong)NSString *name;
@property (nonatomic)int age;
@property (nonatomic, strong)NSString *sex;
@property (nonatomic, strong)NSString *info;
@end
Person.m
import "Person.h"
import <objc/message.h> //一定要导入这个文件
@implementation Person
//分别实现下面这两个方法
//归档
- (void)encodeWithCoder:(NSCoder *)aCoder {
unsigned int count = 0;
//获取属性列表
Ivar *ivars = class_copyIvarList([Person class], &count);
for(int i= 0; i < count; i++) {
//取出对应的成员属性
Ivar ivar = ivars[i];
//获取属性名称
const char *name = ivar_getName(ivar);
NSString *key = [NSString stringWithUTF8String:name];
//归档
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
free(ivars);
}
//解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([Person class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
NSString *key = [NSString stringWithUTF8String:name];
//解档
id value = [aDecoder decodeObjectForKey:key];
//为成员属性赋值
[self setValue:value forKey:key];
}
free(ivars);
}
return self;
}
@end
//在一个控制器中
import "ViewController.h"
import <objc/message.h>
import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Ivar runtime里面 Ivar代表成员变量(成员属性)
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([Person class], &count);
//获取其中一个属性名称
Ivar ivar = ivars[0];
const char *name = ivar_getName(ivar);
NSLog(@"成员属性个数:%d。成员属性名是:%s", count,name);
}
//下面两个保存和读取方法是storyboard拖拽的
-
(IBAction)saveData:(id)sender {
Person *p = [[Person alloc]init];
p.name = @"hervey";
p.age = 18;
p.info = @"http://www.jianshu.com/u/b0bdd6db3cc8";
//存储沙盒
NSString *temp = NSTemporaryDirectory();
NSString *filePath = [temp stringByAppendingPathComponent:@"hervey.txt"];
//归档
[NSKeyedArchiver archiveRootObject:p toFile:filePath];
NSLog(@"沙盒地址:%@",filePath);
} -
(IBAction)readData:(id)sender {
//路径
NSString *temp = NSTemporaryDirectory();
NSString *filePath = [temp stringByAppendingPathComponent:@"hervey.txt"];
//解档
Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"My name is %@ and age is %d.",p.name, p.age);
NSLog(@"简书地址:%@",p.info);
}