第十七篇归档缓存模型

Posted 久冬不雨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第十七篇归档缓存模型相关的知识,希望对你有一定的参考价值。

.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 = [[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 = [[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 = [[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 = [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

 

以上是关于第十七篇归档缓存模型的主要内容,如果未能解决你的问题,请参考以下文章

Linux篇第十七篇——网络基础(概念+协议的认识+OSI七层模型+TCP/IP五层模型+网络传输的流程)

Linux篇第十七篇——网络基础(概念+协议的认识+OSI七层模型+TCP/IP五层模型+网络传输的流程)

Python之路第十七篇Django进阶篇

Python之路第十七篇:Django进阶篇

Python之路第十七篇:Django进阶篇

Python之路第十七篇:Django进阶篇