目标:向沙盒中存储一个自定义的对象 例如model类
方案:使用归解档
还是直接上代码吧,说明性文字实在弱项
1.使用归解档 需要遵守一个协议 <NSCoding> 这里的age属性为什么要声明成NSNumber类型 主要是为了后面的runtime .h
#import <Foundation/Foundation.h>
@interface PYHModel : NSObject<NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, strong) NSNumber *sex;
@property (nonatomic, copy) NSString *address;
- (instancetype)initWithDict:(NSDictionary *)dict;
@end
2.实现协议方法 这里我用了一个runtime 偷个懒不用所有属性都写一遍 .m
- (NSArray *)allPropertyKey {
if (!_allPropertyKey) {
NSMutableArray *pps = [NSMutableArray array];
//获取当前类所有属性 进行初始化
unsigned int outCount = 0;
objc_property_t *models = class_copyPropertyList([self class], &outCount);//获取所有属性
for (unsigned int i = 0; i < outCount; i ++) {
objc_property_t model = models[i];//获取指定下标属性
NSString *propertyKey = [NSString stringWithUTF8String:property_getName(model)];
[pps addObject:propertyKey];
}
free(models);
_allPropertyKey = pps.copy;
}
return _allPropertyKey;
}
//解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
[self.allPropertyKey enumerateObjectsUsingBlock:^(NSString * _Nonnull propertyKey, NSUInteger idx, BOOL * _Nonnull stop) {
id propertyValue = [aDecoder decodeObjectForKey:propertyKey];
[self setValue:propertyValue forKey:propertyKey];
}];
}
return self;
}
//归档
- (void)encodeWithCoder:(NSCoder *)aCoder {
[self.allPropertyKey enumerateObjectsUsingBlock:^(NSString * _Nonnull propertyKey, NSUInteger idx, BOOL * _Nonnull stop) {
id propertyValue = [self valueForKey:propertyKey];
[aCoder encodeObject:propertyValue forKey:propertyKey];
}];
}
3.当然进行归解档也是需要调用一个api的
//归档 写入沙盒 系统方法
PYHModel *model = [[PYHModel alloc]initWithDict:@{@"name":@"pyh",@"address":@"hangzhoubingjiang",@"age":@28,@"sex":@"1"}];
BOOL result = [NSKeyedArchiver archiveRootObject:model toFile:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"model"]];
NSLog(@"%@",result ? @"归档成功" : @"归档失败");
//解档 从沙盒读取对象 系统方法
PYHModel *model = [NSKeyedUnarchiver unarchiveObjectWithFile:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"model"]];
NSLog(@"%@",model);
到这归解档的使用就结束了
demo:https://github.com/DeepSeaGhost/archiver
网友评论