首页 > 代码库 > 第十七篇、归档缓存模型

第十七篇、归档缓存模型

.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

 

第十七篇、归档缓存模型