一、归档 保存model
//Person是model
Person *p = [Person new];
p.age = 18;
p.name = @"小明";
//放到temp
NSString *temp = NSTemporaryDirectory();
NSString *filePath = [temp stringByAppendingString:@"h.h"];
//归档--存储
[NSKeyedArchiver archiveRootObject:p toFile:filePath];
//🐷解档
NSString *temp = NSTemporaryDirectory();
NSString *filePath = [temp stringByAppendingString:@"h.h"];
Person * p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@今年%d岁了",p.name,p.age);
二、NSUserDefaults 本地存储model
Person *p = [Person new];
p.age = 18;
p.name = @"小明";
//将student类型变为NSData类型,保存
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:p];
DEF_PERSISTENT_SET_OBJECT(data, @"Person");
//取model
Person *person = [NSKeyedUnarchiver unarchiveObjectWithData:DEF_PERSISTENT_GET_OBJECT(@"Person")];
NSLog(@"%@今年%d岁了",person.name,person.age);
Person类
//Person.h Person是直接继承自NSObject,没有实现copyWithZone(Person实例对象copy会报错)
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding>
/** 年龄 **/
@property (nonatomic,assign) int age;
/** 名字 **/
@property (nonatomic,copy) NSString* name;
@end
//Person.m
//当外面归档这个对象的时候,就会调用这个方法,如果不实现就会报错!!
- (void)encodeWithCoder:(NSCoder *)coder
{
// [coder encodeObject:_name forKey:@"name"];
// [coder encodeInt:_age forKey:@"age"];
//利用Runtime来归档
unsigned int count = 0;
//C语言里面,如果传基本数据类型的指针!那么都是需要在函数内部改变它的值
Ivar *ivars = class_copyIvarList([Person class], &count);
// NSLog(@"%d",count);//.m照样能够拿到
for (int i = 0; i< count; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
// NSLog(@"%s",name);
NSString *key = [NSString stringWithUTF8String:name];
//属性的值!!KVC 哥们给我一个名称,我就能拿到一个值
[coder encodeObject:[self valueForKey:key] forKey:key];
}
//在C语言里面,但凡看到new,create,copy函数需要释放指针!!
free(ivars);
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
// //写解档的代码
// _name = [coder decodeObjectForKey:@"name"];
// _age = [coder decodeIntForKey:@"age"];
//利用Runtime来解档
unsigned int count = 0;
//C语言里面,如果传基本数据类型的指针!那么都是需要在函数内部改变它的值
Ivar *ivars = class_copyIvarList([Person class], &count);
// NSLog(@"%d",count);//.m照样能够拿到
for (int i = 0; i< count; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
// NSLog(@"%s",name);
NSString *key = [NSString stringWithUTF8String:name];
//解档
id value = [coder decodeObjectForKey:key];
//利用KVC 设置
[self setValue:value forKey:key];
}
free(ivars);
}
return self;
}
声明的宏
/**
* 永久存储对象
*
* NSUserDefaults保存的文件在tmp文件夹里
*
* @param object 需存储的对象
* @param key 对应的key
*/
#define DEF_PERSISTENT_SET_OBJECT(object, key) \
({ \
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; \
[defaults setObject:object forKey:key]; \
[defaults synchronize]; \
})
/**
* 取出永久存储的对象
*
* @param key 所需对象对应的key
* @return key 所对应的对象
*/
#define DEF_PERSISTENT_GET_OBJECT(key) [[NSUserDefaults standardUserDefaults] objectForKey:key]
推荐一篇文章,写的很好。
编程小翁:https://www.jianshu.com/p/fed1dcb1ac9f?utm_campaign=hugo&utm_medium=reader_share&utm_content=note&utm_source=weixin-friends