相较于NSUserDefaults和NSFileManager,归档解档可以存储model模型。比如平时项目最常用的归档解档就是保存用户相关信息
1.新建一个基类MSModel
#import <Foundation/Foundation.h>
@interface MSModel : NSObject <NSCoding>
@end
#import "MSModel.h"
#import <objc/runtime.h>
@implementation MSModel
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
u_int count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i++) {
const char *propertyName = property_getName(properties[i]);
NSString *key = [NSString stringWithUTF8String:propertyName];
[self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
free(properties);
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
u_int count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i++) {
const char *propertyName = property_getName(properties[i]);
NSString *key = [NSString stringWithUTF8String:propertyName];
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
free(properties);
}
@end
2.以后创建需要缓存的模型就继承自MSModel即可实现缓存的目的
#import "MSModel.h"
@interface CacheModel : MSModel
@property (nonatomic, copy, nullable) NSString *name;
@property (nonatomic, copy, nullable) NSString *ID;
@property (nonatomic, assign) NSInteger *age;
@property (nonatomic, assign) BOOL gender;
@end
3.在控制器中实现缓存
// 归档
CacheModel *model = [CacheModel new];
model.name = @"moses";
model.ID = @"10086";
model.age = 18;
model.gender = 1;
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentPath stringByAppendingPathComponent:@"cache001"];
[NSKeyedArchiver archiveRootObject:model toFile:filePath];
// 解档
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentPath stringByAppendingPathComponent:@"cache001"];
CacheModel *model = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@--%@--%d--%d", model.name, model.ID, model.age, model.gender);
网友评论