iOS - LocalCache 本地数据缓存
1、自定义方式本地数据缓存
1.1 自定义缓存 1
沙盒路径下的 Library/Caches 用来存放缓存文件,保存从网络下载的请求数据,后续仍然需要继续使用的文件,例如网络下载的离线数据,图片,视频文件等。该目录中的文件系统不会自动删除,可以做离线访问。它的存放时间比 tmp 下的长,但是不如 Library 下的其它目录。总的来说 Caches 目录下存放的数据不能是应用程序运行所必需的,但是能提高应用访问性能的。可写入应用支持文件,保存应用程序再次启动需要的信息。iTunes 不会对这个目录的内容进行备份。要求程序员必需提供一个完善的清除缓存目录的 "解决方案"。
Objective-C
// 写缓存 - (void)writeLocalCacheData:(NSData *)data withKey:(NSString *)key { // 设置存储路径
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]
stringByAppendingPathComponent:key]; // 判读缓存数据是否存在
if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) { // 删除旧的缓存数据
[[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
} // 存储新的缓存数据
[data writeToFile:cachesPath atomically:YES];
} // 读缓存 - (NSData *)readLocalCacheDataWithKey:(NSString *)key { NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]
stringByAppendingPathComponent:key]; // 判读缓存数据是否存在
if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) { // 读取缓存数据
return [NSData dataWithContentsOfFile:cachesPath];
} return nil;
} // 删缓存 - (void)deleteLocalCacheDataWithKey:(NSString *)key { NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]
stringByAppendingPathComponent:key]; // 判读缓存数据是否存在
if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) { // 删除缓存数据
[[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
}
}
Swift
// 写缓存 func writeLocalCacheData(data:NSData, withKey key:String) { // 设置存储路径
let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
.stringByAppendingString("/\(key)") // 判读缓存数据是否存在
if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) { // 删除旧的缓存数据
try! NSFileManager.defaultManager().removeItemAtPath(cachesPath)
} // 存储新的缓存数据
data.writeToFile(cachesPath, atomically: true)
} // 读缓存 func readLocalCacheDataWithKey(key:String) -> NSData? { let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
.stringByAppendingString("/\(key)") // 判读缓存数据是否存在
if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) { // 读取缓存数据
return NSData(contentsOfFile: cachesPath)
} return nil
} // 删缓存 func deleteLocalCacheDataWithKey(key:String) { let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
.stringByAppendingString("/\(key)") // 判读缓存数据是否存在
if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) { // 删除缓存数据
try! NSFileManager.defaultManager().removeItemAtPath(cachesPath)
}
}
1.2 自定义缓存 2
沙盒路径下的 Library/Preferences 常用来放置配置文件、数据文件、模板等应用在运行中与用户相关,而又希望对用户不可见的文件,如系统偏好设置,用户偏好设置等文件。使用 NSUserDefaults 类进行偏好设置文件的创建、读取和修改。
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 方式本地数据缓存
- EGOCache 一个简单、线程安全的基于 key-value 的缓存框架,原生支持 NSString、UI/NSImage、和 NSData,也支持储存任何实现
<NSCoding>
协议的类。 - EGOCache 只有一个类,并且为单例类,只有 EGOCache.h 和 EGOCache.m 两个文件。
- EGOCache 只提供了磁盘缓存,没有提供内存缓存,同时,也提供了清理缓存的方法。
- EGOCache 可以设定缓存过期时间,默认是 1 天,过期的缓存在创建 EGOCache 对象时会被删除。
2.1 添加 EGOCache
Github 网址:https://github.com/enormego/EGOCache
EGOCache 使用 ARC
Objective-C
// 添加第三方库文件
EGOCache-2.1.3 // 包含头文件
#import "EGOCache.h"
Swift
// 添加第三方库文件
EGOCache-2.1.3 // 创建名为 “项目名-Bridging-Header.h” 的桥接头文件,如:
SwiftLocalCache-Bridging-Header.h // 在 TARGETS -> Build Setting -> Swift Compiler - Code generation -> Objective-C Bridging Header 中
// 添加 “项目名/项目名-Bridging-Header.h” 路径,如:
SwiftLocalCache/SwiftLocalCache-Bridging-Header.h // 在创建的桥接头文件中包含头文件
#import "EGOCache.h"
2.2 EGOCache 缓存
Objective-C
// 判断缓存数据是否存在 BOOL hasLocalCache = [[EGOCache globalCache] hasCacheForKey:@"qqCache"]; // 读取缓存数据 NSData *localData = [[EGOCache globalCache] dataForKey:@"qqCache"]; // 存储缓存数据 [[EGOCache globalCache] setData:data forKey:@"qqCache"];
Swift
// 判断缓存数据是否存在 let hasLocalCache = EGOCache.globalCache().hasCacheForKey("qqCache") // 读取缓存数据 let localData = EGOCache.globalCache().dataForKey("qqCache") // 存储缓存数据 EGOCache.globalCache().setData(data, forKey: "qqCache")
2.3 EGOCache 属性方法
判断缓存数据是否存在方法
// 判断指定缓存的数据是否存在
- (BOOL)hasCacheForKey:(NSString* __nonnull)key;
存储缓存数据方法
// 存储 NSData 型数据
- (void)setData:(NSData* __nonnull)data forKey:(NSString* __nonnull)key;
- (void)setData:(NSData* __nonnull)data forKey:(NSString* __nonnull)key
withTimeoutInterval:(NSTimeInterval)timeoutInterval; // 存储 NSString 型数据
- (void)setString:(NSString* __nonnull)aString forKey:(NSString* __nonnull)key;
- (void)setString:(NSString* __nonnull)aString forKey:(NSString* __nonnull)key
withTimeoutInterval:(NSTimeInterval)timeoutInterval; // 存储 UIImage 型数据
- (void)setImage:(UIImage* __nonnull)anImage forKey:(NSString* __nonnull)key;
- (void)setImage:(UIImage* __nonnull)anImage forKey:(NSString* __nonnull)key
withTimeoutInterval:(NSTimeInterval)timeoutInterval; // 存储 PList 型数据
- (void)setPlist:(nonnull id)plistObject forKey:(NSString* __nonnull)key;
- (void)setPlist:(nonnull id)plistObject forKey:(NSString* __nonnull)key
withTimeoutInterval:(NSTimeInterval)timeoutInterval; // 存储 OBject 型数据
- (void)setObject:(nonnull id<NSCoding>)anObject forKey:(NSString* __nonnull)key;
- (void)setObject:(nonnull id<NSCoding>)anObject forKey:(NSString* __nonnull)key
withTimeoutInterval:(NSTimeInterval)timeoutInterval;
读取缓存数据方法
// 读取 NSData 型缓存数据
- (NSData* __nullable)dataForKey:(NSString* __nonnull)key; // 读取 NSString 型缓存数据
- (NSString* __nullable)stringForKey:(NSString* __nonnull)key; // 读取 UIImage 型缓存数据
- (UIImage* __nullable)imageForKey:(NSString* __nonnull)key; // 读取 PList 型缓存数据
- (NSData* __nullable)plistForKey:(NSString* __nonnull)key; // 读取 OBject 型缓存数据
- (nullable id<NSCoding>)objectForKey:(NSString* __nonnull)key;
复制缓存数据方法
// 复制指定缓存数据
- (void)copyFilePath:(NSString* __nonnull)filePath asKey:(NSString* __nonnull)key; - (void)copyFilePath:(NSString* __nonnull)filePath asKey:(NSString* __nonnull)key
withTimeoutInterval:(NSTimeInterval)timeoutInterval;
清除缓存数据方法
// 清除全部缓存数据
- (void)clearCache; // 清除指定缓存的数据
- (void)removeCacheForKey:(NSString* __nonnull)key;
读取缓存信息方法
// 获取指定缓存的缓存时间
- (NSDate* __nullable)dateForKey:(NSString* __nonnull)key; // 获取所有缓存的 key 值
- (NSArray* __nonnull)allKeys;
创建缓存对象方法
// 这种方法创建的缓存对象不是单例类,可以自己设置缓存路径
- (nonnull instancetype)initWithCacheDirectory:(NSString* __nonnull)cacheDirectory;
缓存时间属性
// Default is 1 day
@property(nonatomic) NSTimeInterval defaultTimeoutInterval;
iOS - LocalCache 本地数据缓存的更多相关文章
- Android清除本地数据缓存代码案例
Android清除本地数据缓存代码案例 直接上代码: /* * 文 件 名: DataCleanManager.java * 描 述: 主要功能有清除内/外缓存,清除数据库,清除shar ...
- 微信小程序开发:学习笔记[9]——本地数据缓存
微信小程序开发:学习笔记[9]——本地数据缓存 快速开始 说明 本地数据缓存是小程序存储在当前设备上硬盘上的数据,本地数据缓存有非常多的用途,我们可以利用本地数据缓存来存储用户在小程序上产生的操作,在 ...
- iOS 网络请求数据缓存
1. NSURLCache简介: iOS对NSURLRequest提供了7种缓存策略:(实际上能用的只有4种) NSURLRequestUseProtocolCachePolicy // 默认的缓存策 ...
- 使用SQLite做本地数据缓存的思考
前言 在一个分布式缓存遍地都是的环境下,还讲本地缓存,感觉有点out了啊!可能大家看到标题,就没有想继续看下去的欲望了吧.但是,本地缓存的重要性也是有的! 本地缓存相比分布式缓存确实是比较out和比较 ...
- 【Android】Android清除本地数据缓存代码
最近做软件的时候,遇到了缓存的问题,在网上看到了这个文章,感觉不错.分享给大家看看 文章出处:http://www.cnblogs.com/rayray/p/3413673.html /* * 文 件 ...
- Android清除本地数据缓存代码
/* * 文 件 名: DataCleanManager.java * 描 述: 主要功能有清除内/外缓存,清除数据库,清除sharedPreference,清除files和清除自定义目 ...
- ios 保存本地数据的方法
1. NSString *path = [[NSBundle mainBundle] pathForResource:@"文件名" ofType:@"plist" ...
- [2]项目创建-使用C#.NET开发基于本地数据缓存的PC客户端
1.新建项目->已安装->模板->Visual c#->Windows桌面->Windows窗体应用程序,截图如下: 图中1:输入项目名称-“MoneyNotes”,图中 ...
- [1]开发准备-使用C#.NET开发基于本地数据缓存的PC客户端
小记:本人是PHPer,对C#.NET的开发只能说看得懂,也写得了功能略简单的PC客户端程序,下面的是本人开发一款名叫“理财速记”的PC客户端软件的全过程记录,期间包括比较繁琐的C#.NET资料查询等 ...
随机推荐
- Oracle中merge into的使用
http://blog.csdn.net/yuzhic/article/details/1896878 http://blog.csdn.net/macle2010/article/details/5 ...
- 【jQuery UI 1.8 The User Interface Library for jQuery】.学习笔记.5.Accordion控件
accordion是另一个UI控件,能允许你将一组content加入相互分隔的.能够被浏览者的交互打开或关闭的panels中.因此,它大多数的content在初始化的时候是隐藏的,很像tabs控件.每 ...
- Linux下通过crontab及expect实现自动化处理
版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[+] 目标 为实现每天定时从其他服务器上复制文件到本地,需要使用crontab建立定时任务,并通过scp进行Linux之间的文件复制. ...
- hdwiki 学习笔记 01
一.href =“”里的参数写法 <!--{if $hotname[url]}-->{$hotname[url]} <!--{else}-->index.php?doc-inn ...
- gridview 经典
一.gridview 中弹出超链接 <%--好方法:超链接列中可以直接从数据库获取完整字段,然后选择在当前窗口打开 Target="mainframe" --%> &l ...
- [转]iOS学习之UINavigationController详解与使用(二)页面切换和segmentedController
转载地址:http://blog.csdn.net/totogo2010/article/details/7682433 iOS学习之UINavigationController详解与使用(一)添加U ...
- 多校赛3- Solve this interesting problem 分类: 比赛 2015-07-29 21:01 8人阅读 评论(0) 收藏
H - Solve this interesting problem Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I ...
- Python学习笔记-Day3-文件操作
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True) 打开文件并返回一个 ...
- HDU How many integers can you find 容斥
How many integers can you find Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 ...
- Mysql-学习笔记(==》触发器 十一)
-------触发器-------- USE db;SELECT FROM sss; CREATE TABLE sssbak LIKE sss;SHOW CREATE TABLE sss;SHOW C ...