首页 > 代码库 > 第十七篇、归档缓存模型
第十七篇、归档缓存模型
.h
#import <Foundation/Foundation.h>@interface LocalData : NSObject+ (instancetype)read:(NSString *)name;+ (void)save:(NSString *)name className:(id)className;@end
.m
#import "LocalData.h"@implementation LocalData+ (instancetype)read:(NSString *)name {// NSData *_data = http://www.mamicode.com/[[NSData alloc] initWithContentsOfFile:[self getFilePathWithModelKey:name]];>// //解档辅助类// NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:_data];// //解档出数据模型Student// //解码并解档出model// id model = [unarchiver decodeObjectForKey:name];// //关闭解档// [unarchiver finishDecoding];// return model; //获得保存数据 NSData *getthemeAndAboutData =http://www.mamicode.com/ [[NSUserDefaults standardUserDefaults] objectForKey:name]; //转成模型获取数据 id model = [NSKeyedUnarchiver unarchiveObjectWithData:getthemeAndAboutData]; return model; //return [NSKeyedUnarchiver unarchiveObjectWithFile:[self getFilePathWithModelKey:name]];}+ (void)save:(NSString *)name className:(id)className{// BOOL success = [NSKeyedArchiver archiveRootObject:className toFile:[self getFilePathWithModelKey:name]];// NSLog(@"保存的状态%d",success); ///////////////////////归档// //需要用NSMutableData来中中介// NSMutableData *data = http://www.mamicode.com/[[NSMutableData alloc] init];>// //创建归档辅助类// NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];// //编码// [archiver encodeObject:className forKey:name];// //结束编码// [archiver finishEncoding];// //写入// [data writeToFile:[self getFilePathWithModelKey:name] atomically:YES]; NSData *themeAndAboutData =http://www.mamicode.com/ [NSKeyedArchiver archivedDataWithRootObject:className]; [[NSUserDefaults standardUserDefaults] setObject:themeAndAboutData forKey:name]; [[NSUserDefaults standardUserDefaults] synchronize]; }//得到目录+(NSString *) getFilePathWithModelKey:(NSString *)modelkey{ NSArray *array = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); return [[array objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.archiver",modelkey]]; }@end
第十七篇、归档缓存模型
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。