viewController.m文件的调用
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self encodeObject];
[self decodeObject];
}
- (void)encodeObject{
Person *myPerson = [[Person alloc] init];
myPerson.name = @"yjh";
myPerson.age = 25;
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:myPerson forKey:@"person"];
[archiver finishEncoding];
[data writeToFile:[self filePath] atomically:YES];
}
- (void)decodeObject{
NSData *dataC = [NSData dataWithContentsOfFile:[self filePath]];
NSKeyedUnarchiver *unArch =[[NSKeyedUnarchiver alloc] initForReadingWithData:dataC];
Person *unPerson = [unArch decodeObjectForKey:@"person"];
[unArch finishDecoding];
NSLog(@"dasdf%@",unPerson.name);
}
- (NSString *)filePath{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString* filePath = [path stringByAppendingPathComponent:@"person.data"];
return filePath;
}
person.h 文件
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, strong) NSString *weight;
@end
person.m文件
#import "Person.h"
#import <objc/message.h>
@implementation Person
- (void)encodeWithCoder:(NSCoder *)aCoder{
// runtime方法
unsigned int count = 0; // 等下要把他的传地址进去
Ivar *ivars = class_copyIvarList([self class], &count); // 得到成员变量的指针 和 count的值
for (int i = 0; i < count; i++) {
const char * ivarName = ivar_getName(ivars[i]); // 得到成员变量的名称
NSString *ivar = [NSString stringWithUTF8String:ivarName]; // C语言的转换成OC的NSString
id value = [self valueForKey:ivar]; // kvc得到成员变量的值
[aCoder encodeObject:value forKey:ivar];
}
free(ivars); // 释放C语言的内存空间
// 原来方法
// [aCoder encodeObject:_name forKey:@"name"];
// [aCoder encodeInt:_age forKey:@"age"];
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
// runtime方法
if (self = [super init]) {
unsigned int count = 0;
//获取类中所有成员变量名
Ivar *ivar = class_copyIvarList([self class], &count);
for (int i = 0; i<count; i++) {
Ivar iva = ivar[i];
const char *name = ivar_getName(iva);
NSString *strName = [NSString stringWithUTF8String:name];
//进行解档取值
id value = [aDecoder decodeObjectForKey:strName];
//利用KVC对属性赋值
[self setValue:value forKey:strName];
}
free(ivar);
// 原来方法
// _name = [aDecoder decodeObjectForKey:@"name"];
// _age = [aDecoder decodeIntForKey:@"age"];
}
return self;
}
@end