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來作本地數據持久化緩存:
保存到本地後的樣子是這樣的:
而後再是經過banners
這個惟一Key來讀取緩存:網絡
願全部人不會再掉入我曾踩過的那些坑!
但願這篇文章能給你帶來一點幫助!atom