iOS 归档缓存

代码如下:

  • 头文件定义
    1
    2
    3
    4
    // 归档缓存内容
    + (void)archiverObject:(id)object byKey:(NSString *)key withPath:(NSString *)path;
    // 解归档缓存内容
    + (id)unarchiverObjectByKey:(NSString *)key withPath:(NSString *)path;
  • 方法实现
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    + (void)archiverObject:(id)object byKey:(NSString *)key withPath:(NSString *)path{
    //初始化存储对象信息的data
    NSMutableData *data = [NSMutableData data];
    //创建归档工具对象
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    //开始归档
    [archiver encodeObject:object forKey:key];
    //结束归档
    [archiver finishEncoding];
    //写入本地地址
    NSString *resultStr = [self destPath:path];
    [data writeToFile:resultStr atomically:YES];
    }

    + (NSString *)destPath:(NSString *)path{
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    NSString *destPath = [[docPath stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:path];
    NSLog(@"%@", destPath);
    return destPath;
    }

    + (id)unarchiverObjectByKey:(NSString *)key withPath:(NSString *)path{
    NSString *resultStr = [self destPath:path];
    NSData *data = [NSData dataWithContentsOfFile:resultStr];
    //创建反归档对象
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    //接收反归档得到的对象
    id object = [unarchiver decodeObjectForKey:key];
    return object;
    }
  • 使用实例
    1
    2
    3
    4
    5
    NSDictionary *dict = @{@"1":@"ding", @"2":@"guan", @"3":@"xiong"};
    [TestObj archiverObject:dict byKey:@"cache" withPath:@"cache.plist"];

    NSDictionary *result = [TestObj unarchiverObjectByKey:@"cache" withPath:@"cache.plist"];
    NSLog(@"***::%@", result);
-------------本文结束感谢您的阅读-------------
最近的文章

iOS 唤起APP之Universal Link(通用链接)

iOS 9之前,一直使用的是URL Schemes技术来从外部对App进行跳转,但是iOS系统中进行URL Schemes跳转的时候如果没有安装App,会提示Cannot open Page的提示,而且当注册有多个scheme相同的时候,目前没有办法区分,但是从iOS 9起可以使用Universa …

继续阅读
更早的文章

iOS UIView分类

.h内容1234567891011121314151617181920212223- (CGPoint)origin;- (void)setOrigin:(CGPoint)point;- (CGSize)size;- (void)setSize:(CGSize)size;- (CGFloat)x; …

继续阅读