iOS - LocalCache 本地数据缓存
1、自定義方式本地?cái)?shù)據(jù)緩存
1.1 自定義緩存 1
沙盒路徑下的 Library/Caches 用來(lái)存放緩存文件,保存從網(wǎng)絡(luò)下載的請(qǐng)求數(shù)據(jù),后續(xù)仍然需要繼續(xù)使用的文件,例如網(wǎng)絡(luò)下載的離線數(shù)據(jù),圖片,視頻文件等。該目錄中的文件系統(tǒng)不會(huì)自動(dòng)刪除,可以做離線訪問。它的存放時(shí)間比 tmp 下的長(zhǎng),但是不如 Library 下的其它目錄。總的來(lái)說(shuō) Caches 目錄下存放的數(shù)據(jù)不能是應(yīng)用程序運(yùn)行所必需的,但是能提高應(yīng)用訪問性能的。可寫入應(yīng)用支持文件,保存應(yīng)用程序再次啟動(dòng)需要的信息。iTunes 不會(huì)對(duì)這個(gè)目錄的內(nèi)容進(jìn)行備份。要求程序員必需提供一個(gè)完善的清除緩存目錄的 "解決方案"。
-
Objective-C
// 寫緩存- (void)writeLocalCacheData:(NSData *)data withKey:(NSString *)key {// 設(shè)置存儲(chǔ)路徑NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:key];// 判讀緩存數(shù)據(jù)是否存在if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {// 刪除舊的緩存數(shù)據(jù)[[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];}// 存儲(chǔ)新的緩存數(shù)據(jù)[data writeToFile:cachesPath atomically:YES];}// 讀緩存- (NSData *)readLocalCacheDataWithKey:(NSString *)key {NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:key];// 判讀緩存數(shù)據(jù)是否存在if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {// 讀取緩存數(shù)據(jù)return [NSData dataWithContentsOfFile:cachesPath];}return nil;}// 刪緩存- (void)deleteLocalCacheDataWithKey:(NSString *)key {NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:key];// 判讀緩存數(shù)據(jù)是否存在if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {// 刪除緩存數(shù)據(jù)[[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];}} -
Swift
// 寫緩存func writeLocalCacheData(data:NSData, withKey key:String) {// 設(shè)置存儲(chǔ)路徑let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0].stringByAppendingString("/\(key)")// 判讀緩存數(shù)據(jù)是否存在if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) {// 刪除舊的緩存數(shù)據(jù)try! NSFileManager.defaultManager().removeItemAtPath(cachesPath)}// 存儲(chǔ)新的緩存數(shù)據(jù)data.writeToFile(cachesPath, atomically: true)}// 讀緩存func readLocalCacheDataWithKey(key:String) -> NSData? {let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0].stringByAppendingString("/\(key)")// 判讀緩存數(shù)據(jù)是否存在if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) {// 讀取緩存數(shù)據(jù)return NSData(contentsOfFile: cachesPath)}return nil}// 刪緩存func deleteLocalCacheDataWithKey(key:String) {let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0].stringByAppendingString("/\(key)")// 判讀緩存數(shù)據(jù)是否存在if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) {// 刪除緩存數(shù)據(jù)try! NSFileManager.defaultManager().removeItemAtPath(cachesPath)}}
1.2 自定義緩存 2
沙盒路徑下的 Library/Preferences 常用來(lái)放置配置文件、數(shù)據(jù)文件、模板等應(yīng)用在運(yùn)行中與用戶相關(guān),而又希望對(duì)用戶不可見的文件,如系統(tǒng)偏好設(shè)置,用戶偏好設(shè)置等文件。使用 NSUserDefaults 類進(jìn)行偏好設(shè)置文件的創(chuàng)建、讀取和修改。
-
Objective-C
// 寫緩存- (void)saveCacheData:(NSData *)data withType:(int)type andID:(int)_id {NSUserDefaults *setting = [NSUserDefaults standardUserDefaults];NSString *key = [NSString stringWithFormat:@"detail-%d-%d", type, _id];[setting setObject:data forKey:key];[setting synchronize];}// 讀緩存- (NSData *)getCacheDataWithType:(int)type andID:(int)_id {NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];NSString *key = [NSString stringWithFormat:@"detail-%d-%d", type, _id];return [setting objectForKey:key];}// 刪緩存- (void)removeCacheDataWith:(int)type andID:(int)_id {NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];NSString *key = [NSString stringWithFormat:@"detail-%d-%d", type, _id];[setting removeObjectForKey:key];[setting synchronize];} -
Swift
// 寫緩存func saveCacheData(data:NSData, withType type:Int, andID _id:Int) {let setting = NSUserDefaults.standardUserDefaults()let key = String(format: "detail-%d-%d", type, _id)setting.setObject(data, forKey: key)setting.synchronize()}// 讀緩存func getCacheDataWithType(type:Int, andID _id:Int) -> NSData? {let setting = NSUserDefaults.standardUserDefaults()let key = String(format: "detail-%d-%d", type, _id)return setting.objectForKey(key) as? NSData}// 刪緩存func removeCacheDataWithType(type:Int, andID _id:Int) {let setting = NSUserDefaults.standardUserDefaults()let key = String(format: "detail-%d-%d", type, _id)setting.removeObjectForKey(key)setting.synchronize()}
2、EGOCache 方式本地?cái)?shù)據(jù)緩存
- EGOCache 一個(gè)簡(jiǎn)單、線程安全的基于 key-value 的緩存框架,原生支持 NSString、UI/NSImage、和 NSData,也支持儲(chǔ)存任何實(shí)現(xiàn) <NSCoding> 協(xié)議的類。
- EGOCache 只有一個(gè)類,并且為單例類,只有 EGOCache.h 和 EGOCache.m 兩個(gè)文件。
- EGOCache 只提供了磁盤緩存,沒有提供內(nèi)存緩存,同時(shí),也提供了清理緩存的方法。
- EGOCache 可以設(shè)定緩存過(guò)期時(shí)間,默認(rèn)是 1 天,過(guò)期的緩存在創(chuàng)建 EGOCache 對(duì)象時(shí)會(huì)被刪除。
2.1 添加 EGOCache
Github 網(wǎng)址:https://github.com/enormego/EGOCache
EGOCache 使用 ARC
-
Objective-C
// 添加第三方庫(kù)文件EGOCache-2.1.3// 包含頭文件#import "EGOCache.h" -
Swift
// 添加第三方庫(kù)文件EGOCache-2.1.3// 創(chuàng)建名為 “項(xiàng)目名-Bridging-Header.h” 的橋接頭文件,如:SwiftLocalCache-Bridging-Header.h// 在 TARGETS -> Build Setting -> Swift Compiler - Code generation -> Objective-C Bridging Header 中// 添加 “項(xiàng)目名/項(xiàng)目名-Bridging-Header.h” 路徑,如:SwiftLocalCache/SwiftLocalCache-Bridging-Header.h// 在創(chuàng)建的橋接頭文件中包含頭文件#import "EGOCache.h"
2.2 EGOCache 緩存
-
Objective-C
// 判斷緩存數(shù)據(jù)是否存在BOOL hasLocalCache = [[EGOCache globalCache] hasCacheForKey:@"qqCache"];// 讀取緩存數(shù)據(jù)NSData *localData = [[EGOCache globalCache] dataForKey:@"qqCache"];// 存儲(chǔ)緩存數(shù)據(jù)[[EGOCache globalCache] setData:data forKey:@"qqCache"]; -
Swift
// 判斷緩存數(shù)據(jù)是否存在let hasLocalCache = EGOCache.globalCache().hasCacheForKey("qqCache")// 讀取緩存數(shù)據(jù)let localData = EGOCache.globalCache().dataForKey("qqCache")// 存儲(chǔ)緩存數(shù)據(jù)EGOCache.globalCache().setData(data, forKey: "qqCache")
2.3 EGOCache 屬性方法
-
判斷緩存數(shù)據(jù)是否存在方法
// 判斷指定緩存的數(shù)據(jù)是否存在- (BOOL)hasCacheForKey:(NSString* __nonnull)key; -
存儲(chǔ)緩存數(shù)據(jù)方法
// 存儲(chǔ) NSData 型數(shù)據(jù)- (void)setData:(NSData* __nonnull)data forKey:(NSString* __nonnull)key;- (void)setData:(NSData* __nonnull)data forKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval;// 存儲(chǔ) NSString 型數(shù)據(jù)- (void)setString:(NSString* __nonnull)aString forKey:(NSString* __nonnull)key;- (void)setString:(NSString* __nonnull)aString forKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval;// 存儲(chǔ) UIImage 型數(shù)據(jù)- (void)setImage:(UIImage* __nonnull)anImage forKey:(NSString* __nonnull)key;- (void)setImage:(UIImage* __nonnull)anImage forKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval;// 存儲(chǔ) PList 型數(shù)據(jù)- (void)setPlist:(nonnull id)plistObject forKey:(NSString* __nonnull)key;- (void)setPlist:(nonnull id)plistObject forKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval;// 存儲(chǔ) OBject 型數(shù)據(jù)- (void)setObject:(nonnull id<NSCoding>)anObject forKey:(NSString* __nonnull)key;- (void)setObject:(nonnull id<NSCoding>)anObject forKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval; -
讀取緩存數(shù)據(jù)方法
// 讀取 NSData 型緩存數(shù)據(jù)- (NSData* __nullable)dataForKey:(NSString* __nonnull)key;// 讀取 NSString 型緩存數(shù)據(jù)- (NSString* __nullable)stringForKey:(NSString* __nonnull)key;// 讀取 UIImage 型緩存數(shù)據(jù)- (UIImage* __nullable)imageForKey:(NSString* __nonnull)key;// 讀取 PList 型緩存數(shù)據(jù)- (NSData* __nullable)plistForKey:(NSString* __nonnull)key;// 讀取 OBject 型緩存數(shù)據(jù)- (nullable id<NSCoding>)objectForKey:(NSString* __nonnull)key; -
復(fù)制緩存數(shù)據(jù)方法
// 復(fù)制指定緩存數(shù)據(jù) - (void)copyFilePath:(NSString* __nonnull)filePath asKey:(NSString* __nonnull)key;- (void)copyFilePath:(NSString* __nonnull)filePath asKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval; -
清除緩存數(shù)據(jù)方法
// 清除全部緩存數(shù)據(jù)- (void)clearCache;// 清除指定緩存的數(shù)據(jù)- (void)removeCacheForKey:(NSString* __nonnull)key; -
讀取緩存信息方法
// 獲取指定緩存的緩存時(shí)間- (NSDate* __nullable)dateForKey:(NSString* __nonnull)key;// 獲取所有緩存的 key 值- (NSArray* __nonnull)allKeys; -
創(chuàng)建緩存對(duì)象方法
// 這種方法創(chuàng)建的緩存對(duì)象不是單例類,可以自己設(shè)置緩存路徑- (nonnull instancetype)initWithCacheDirectory:(NSString* __nonnull)cacheDirectory; -
緩存時(shí)間屬性
// Default is 1 day@property(nonatomic) NSTimeInterval defaultTimeoutInterval;
總結(jié)
以上是生活随笔為你收集整理的iOS - LocalCache 本地数据缓存的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vim编辑器之按键说明
- 下一篇: 梦到脱发严重是什么意思