Demo链接:https://github.com/asd521411/NSCoder.git
还是person类
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@end
person.m==============
#import “Person.h”
#import <objc/runtime.h>
@implementation Person
-
(void)encodeWithCoder:(NSCoder *)aCoder {
//1、常用
// [aCoder encodeObject:_name forKey:@“name”];
// [aCoder encodeInt:_age forKey:@“age”];
//2、如果属性很多
unsigned int count = 0;
Ivar *list = class_copyIvarList(self.class, &count);
for (NSInteger i = 0; i < count; i++) {
Ivar ivar = list[i];
const char *name = ivar_getName(ivar);
NSLog(@"==========%s", name);
NSString *key = [NSString stringWithUTF8String:name];
id value = [self valueForKey:key];
[aCoder encodeObject:value forKey:key];
}
free(list);
} -
(instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
// self.name = [aDecoder decodeObjectForKey:@“name”];
// self.age = [aDecoder decodeIntForKey:@“age”];
unsigned int count = 0;
Ivar *list = class_copyIvarList(self.class, &count);
for (NSInteger i = 0; i < count; i++) {
Ivar ivar = list[i];
NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
//解档
id value = [aDecoder decodeObjectForKey:key];
[self setValue:value forKey:key];
}
free(list);
}
return self;
}
@end
ViewController.m中引用,添加两个按钮,存和取===================
#import “ViewController.h”
#import “Person.h”
/*
*关于runtime
*Ivar:成员变量
*method:成员方法
*/
#import <objc/runtime.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *btn1;
@property (weak, nonatomic) IBOutlet UIButton *btn2;
/**
- 以类为单位,维护一份方法列表
*SEL 编号 --------- IMP 指针(方法实现)
*/
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];
NSLog(@"======%@", NSTemporaryDirectory());
//查看一个累的所有属性列表
unsigned count = 0;
//copy,new,create在堆区(malloc)开辟空间
Ivar *list = class_copyIvarList(Person.class, &count);
Ivar ivar = list[0];
const char *listName = ivar_getName(ivar);
NSLog(@"成员变量个数---------%d=成员变量%s", count, listName);
//防止内存泄漏
free(list);
// Do any additional setup after loading the view, typically from a nib.
} -
(IBAction)btn1:(UIButton *)sender {
Person *per = [[Person alloc] init];
per.name = @“张三”;
per.age = 18;
NSString *temPath = NSTemporaryDirectory();
NSString *filePath = [temPath stringByAppendingPathComponent:@“temp.file”];
[NSKeyedArchiver archiveRootObject:per toFile:filePath];
} -
(IBAction)btn2:(UIButton *)sender {
NSString *temPath = NSTemporaryDirectory();
NSString *filePath = [temPath stringByAppendingPathComponent:@“temp.file”];
Person *per = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"-----------%@-----%d", per.name, per.age);
}
demo地址: