離線緩存
為了用戶的體驗(yàn)镊逝,不需要每次打開App都加載新數(shù)據(jù),或者重新請(qǐng)求數(shù)據(jù),因此需要把每次瀏覽的數(shù)據(jù)保存起來锯蛀,當(dāng)下次打開軟件時(shí),首先從沙盒中加載數(shù)據(jù)次慢;或者當(dāng)軟件未聯(lián)網(wǎng)時(shí)旁涤,也只能從沙盒中加載舊數(shù)據(jù)。
離線數(shù)據(jù)的方法選擇
1.plist文件2.Document路徑3.數(shù)據(jù)庫
由于保存的是大批量數(shù)據(jù)迫像,且會(huì)不停的刷新新數(shù)據(jù)劈愚,因此應(yīng)該選擇數(shù)據(jù)庫來存儲(chǔ)。
離線緩存的思路
當(dāng)?shù)谝淮未蜷_應(yīng)用程序時(shí)闻妓,把界面加載好的數(shù)據(jù)保存到沙盒中
當(dāng)下一次進(jìn)入應(yīng)用程序時(shí)菌羽,首先從沙盒中找
如果沒有網(wǎng)絡(luò),直接加載上次保存的數(shù)據(jù)由缆,或者沒有比較新的數(shù)據(jù)也從沙盒中加載數(shù)據(jù)注祖。
= = ?= ?= ?= = =分 = = = = = = = = = =割 = = = ?= = = = = = =線 = = = = = = = = = = = ?=
本文介紹下緩存plist的項(xiàng)目用法:
Plist緩存一般是一次性緩存的,輕量級(jí)的數(shù)據(jù)都可以存放Plist犁功,以xml的方式存儲(chǔ)沙盒本地氓轰,讀取效率好
直接上代碼:
(1)、簡單創(chuàng)建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是存儲(chǔ)文件的一個(gè)標(biāo)識(shí)J鸺Α!O尴印靴庆!
#program Mark ?==.m 文件代碼
//歸檔
+ (void)archiverObject:(id)object ByKey:(NSString*)key WithPath:(NSString*)path
{
//初始化存儲(chǔ)對(duì)象信息的data
NSMutableData*data = [NSMutableDatadata];
//創(chuàng)建歸檔工具對(duì)象
NSKeyedArchiver*archiver = [[NSKeyedArchiveralloc]initForWritingWithMutableData:data];
//開始?xì)w檔
[archiverencodeObject:objectforKey:key];
//結(jié)束歸檔
[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];
//創(chuàng)建反歸檔對(duì)象
NSKeyedUnarchiver*unarchiver = [[NSKeyedUnarchiveralloc]initForReadingWithData:data];
//接收反歸檔得到的對(duì)象
idobject = [unarchiverdecodeObjectForKey:key];
returnobject;
}
(2)、在網(wǎng)絡(luò)請(qǐng)求的地方實(shí)現(xiàn)將數(shù)據(jù)寫入plist緩存
//獲取本地沙盒路徑
NSArray*path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//獲取完整路徑
NSString*documentsPath = [pathobjectAtIndex:0];
NSString*plistPath = [documentsPathstringByAppendingPathComponent:@"groups.plist"];
NSLog(@"plistPath == %@",plistPath);
//設(shè)置屬性值
//寫入文件
[self.friendsArraywriteToFile:plistPathatomically:YES];