(1)写成文件,用text或plist文件进行数据储存
1.写一个工具类,用以获取文件的路径
/**
* 获取Documents文件夹路径
*
* @return 文件夹路径
*/
+ (NSString *)getDocumentsFolderPath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
/**
* 获取Documents文件路径
*
* @param fileName 文件名称
*
* @return 文件路径
*/
+ (NSString *)getDocumentsFilePath:(NSString *)fileName
{
return [[self getDocumentsFolderPath] stringByAppendingPathComponent:fileName];
}
2.在网络成功请求数据后,将数据存起来,写成文件
//dataDict 是网络请求回来的数据字典
//这里是调用上面工具类的方法,获取文件路径(自定义文件的名字)
NSString *path = [PathService getDocumentsFilePath:@"data.plist"];
[dataDict writeToFile:path atomically:YES];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey];
[[NSFileManager defaultManager] setAttributes:attributes
ofItemAtPath:path
error:nil];
3.在下次打开App,可以先加载缓存或在网络不好时,展示缓存内容
NSString *systemPath = [PathService getDocumentsFilePath:@"<pre name="code" class="objc">data.plist"];
//这里的字典就是之前网络请求成功的数据
NSDictionary *systemData = [NSDictionary dictionaryWithContentsOfFile:systemPath];
(2)第一种是简单的对请求的数据进行储存,如果需要对不同用户做不同的缓存,搭建数据库进行数据缓存
使用FMDB或者CoreData搭建数据库,这里不详细介绍。
(3)缓存清除
//把要清除的文件名写到这,如果全部都清除,遍历缓存文件夹,全部清除即可。
NSArray *pathArray = @[@"NormalBidListInfo.txt",@"ActivityBidListInfo.txt"];
for (NSString *pathName in pathArray) {
NSString *path = [PathService getDocumentsFilePath:pathName];
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:path]) {
DDLogInfo(@"文件不存在:%@",path);
}
NSError *err;
BOOL deleteSuccess = [manager removeItemAtPath:path error:&err];
if (!deleteSuccess) {
DDLogInfo(@"文件删除失败:\nfilePath:%@\nerror:%@",path,err);
}
数据库的缓存清除,调用数据库执行清除表数据sql语句即可。