【Object-C】简单实现plist离线缓存数据
离线缓存
为了用户的体验,不需要每次打开App都加载新数据,或者重新请求数据,因此需要把每次浏览的数据保存起来,当下次打开软件时,首先从沙盒中加载数据;或者当软件未联网时,也只能从沙盒中加载旧数据。
离线数据的方法选择
1.plist文件2.Document路径3.数据库
由于保存的是大批量数据,且会不停的刷新新数据,因此应该选择数据库来存储。
离线缓存的思路
当第一次打开应用程序时,把界面加载好的数据保存到沙盒中
当下一次进入应用程序时,首先从沙盒中找
如果没有网络,直接加载上次保存的数据,或者没有比较新的数据也从沙盒中加载数据。
= = = = = = =分 = = = = = = = = = =割 = = = = = = = = = =线 = = = = = = = = = = = =
本文介绍下缓存plist的项目用法:
Plist缓存一般是一次性缓存的,轻量级的数据都可以存放Plist,以xml的方式存储沙盒本地,读取效率好
直接上代码:
(1)、简单创建plist归档的工具类
归档、反归档工具#program Mark ==.h 文件 代码
#import
@interfaceASArchiverTools :NSObject
//归档的工具方法
+ (void)archiverObject:(id)object ByKey:(NSString*)key
WithPath:(NSString*)path;
+ (id)unarchiverObjectByKey:(NSString*)key
WithPath:(NSString*)path;
@end
说明:方法中的key是存储文件的一个标识!!!!
#program Mark ==.m 文件代码
//归档
+ (void)archiverObject:(id)object ByKey:(NSString*)key WithPath:(NSString*)path
{
//初始化存储对象信息的data
NSMutableData*data = [NSMutableDatadata];
//创建归档工具对象
NSKeyedArchiver*archiver = [[NSKeyedArchiveralloc]initForWritingWithMutableData:data];
//开始归档
[archiverencodeObject:objectforKey:key];
//结束归档
[archiverfinishEncoding];
//写入本地
NSString*docPath =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES).lastObject;
NSString*destPath = [[docPathstringByAppendingPathComponent:@"Caches"]stringByAppendingPathComponent:path];
NSLog(@"destPath == %@",destPath);
[datawriteToFile:destPathatomically:YES];
}
//反归档
+ (id)unarchiverObjectByKey:(NSString*)key WithPath:(NSString*)path
{
NSString*docPath =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES).lastObject;
NSString*destPath = [[docPathstringByAppendingPathComponent:@"Caches"]stringByAppendingPathComponent:path];
NSLog(@"destPath == %@",destPath);
NSData*data = [NSDatadataWithContentsOfFile:destPath];
//创建反归档对象
NSKeyedUnarchiver*unarchiver = [[NSKeyedUnarchiveralloc]initForReadingWithData:data];
//接收反归档得到的对象
idobject = [unarchiverdecodeObjectForKey:key];
returnobject;
}
(2)、在网络请求的地方实现将数据写入plist缓存
//获取本地沙盒路径
NSArray*path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//获取完整路径
NSString*documentsPath = [pathobjectAtIndex:0];
NSString*plistPath = [documentsPathstringByAppendingPathComponent:@"groups.plist"];
NSLog(@"plistPath == %@",plistPath);
//设置属性值
//写入文件
[self.friendsArraywriteToFile:plistPathatomically:YES];
实现效果