iOS开发系列--数据缓存那些小技巧

APP开发中,常常须要对数据做缓存处理,以便于在手机网络不佳时,能做一个离线预加载,提升用户体验。
最先遇到这类需求的时候,我使用的是Sqlite。须要建立数据库,对数据做大量的处理,过程很是繁琐。并且在使用Sqlite时,还常常操做不当,形成数据锁死,进而致使没法正常对数据进行读写操做。
因为当时本身经验不足,没有其它更好的办法,一直在这个坑里跳不出去。直到有一天,终于发现了一个方便简捷的方式去对数据做缓存处理。这就是今天所介绍的方法:使用NSKeyedArchiver做数据持久化。数据库

归档是一个数据持久化的过程,该过程用某种格式来保存一个或多个对象,以便之后还原这些对象。
直接上代码吧
首页是JsonCacheData.h文件数组

#import <Foundation/Foundation.h>

@interface JsonCacheData : NSObject

/**
 *  防止备份到iTunes
 *
 *  @param URL 本地Path
 *
 *  @return 是否成功
 */
+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL;

/**
 *  保存数据到本地
 *
 *  @param data 字典或数组
 *  @param key  经过Key保存或读取
 *
 *  @return 是否成功
 */
+ (BOOL)writePlistWithData:(id)data saveKey:(NSString *)key;

/**
 *  清除数据
 *
 *  @param key  经过Key清除
 *
 *  @return 是否成功
 */
+ (BOOL)clearWithKey:(NSString *)key;

/**
 *  经过Key读取本地缓存
 *
 *  @param key Key
 *
 *  @return 字典或数组
 */
+ (id)readPlistWithKey:(NSString *)key;

@end

JsonCacheData.m文件缓存

#import "JsonCacheData.h"

//获取Cache目录路径
#define CACHEPATH       [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]

@implementation JsonCacheData

//防止备份到iTunes和iCloud(上架审核必备)
+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    if ([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]) {
        NSError *error = nil;
        BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error];
        if(!success){
            NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
        }
        return success;
    }
    return YES;
}

#pragma mark 缓存数据
+ (BOOL)writePlistWithData:(id)data saveKey:(NSString *)key
{
    BOOL success;
    NSString *path = [[CACHEPATH stringByAppendingPathComponent:key] stringByAppendingString:@"CacheData.plist"];//获取路径
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断是否存在,不存在则建立路径
    if (![fileManager fileExistsAtPath:path]) {
        [fileManager createFileAtPath:path contents:nil attributes:nil];
    }
    
    NSData *cacheData = [NSKeyedArchiver archivedDataWithRootObject:data];
    success = [cacheData writeToFile:path atomically:YES];
    [self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
    NSLog(@"Key: %@ , 数据缓存 %@", key, success ? @"成功" : @"失败");
    return success;
}

#pragma mark 清除缓存
+ (BOOL)clearWithKey:(NSString *)key
{
    NSString *path = [[CACHEPATH stringByAppendingPathComponent:key] stringByAppendingString:@"CacheData.plist"];//获取路径
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断是否存在
    if (![fileManager fileExistsAtPath:path]) {
        return NO;
    }
    else {
        return [fileManager removeItemAtPath:path error:nil];
    }
}

#pragma mark 读取缓存
+ (id)readPlistWithKey:(NSString *)key
{
    NSString *path = [[CACHEPATH stringByAppendingPathComponent:key] stringByAppendingString:@"CacheData.plist"];//获取路径
    id object = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    return object;
}

@end

接下来看下实际的使用状况:
经过接口获得的Json数据直接传入进来,用banners这个惟一Key来作本地数据持久化缓存:
缓存.png
保存到本地后的样子是这样的:
plist.png
而后再是经过banners这个惟一Key来读取缓存:
读取.png网络


愿全部人不会再掉入我曾踩过的那些坑!
但愿这篇文章能给你带来一点帮助!atom

相关文章
相关标签/搜索