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


愿所有人不會再掉入我曾踩過的那些坑!
希望這篇文章能給你帶來一點幫助!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容