OSChina_IOS版客户端笔记(四)_程序数据、缓存的管理
為什么80%的碼農(nóng)都做不了架構師?>>> ??
??????程序的數(shù)據(jù)緩存問題。首先常見的程序數(shù)據(jù)可以分為以下幾種:??????· 列表、表格等在線請求的動態(tài)數(shù)據(jù)
??????· 圖片數(shù)據(jù),可以是列表中在線請求的
??????· 用戶信息、程序設置、程序版本信息等
??????列表數(shù)據(jù)的緩存:
?????? 觀察OSChina的iOS版發(fā)現(xiàn),每次切換UISegmentController后都會進行數(shù)據(jù)的在線請求,而沒有使用緩存數(shù)據(jù)(也可能是有某個代碼開關本人沒看清楚吧)。總之這篇文章也不是基于OSChina的iOS客戶端的,而是從博主目前已完成的一個項目中抽取出來的。功能要求:
??????1.由于列表包含了下拉刷新功能,所以在每次切換UISegment時,不進行數(shù)據(jù)的在線請求,直接使用緩存數(shù)據(jù),用戶手動拖動列表觸發(fā)下拉刷新時,才進行數(shù)據(jù)的在線更新(先清空原本所有的緩存文件,在從第一頁開始重新緩存)
??????2.如果某個頁面還沒有進行數(shù)據(jù)緩存,那么此時我們也就沒有緩存數(shù)據(jù)可用了,必須進行數(shù)據(jù)的在線請求。這種情況通常在程序第一次安裝時發(fā)生。
??????這里以Json格式的列表數(shù)據(jù)為例子,討論一下實現(xiàn)細節(jié):
??????以下是緩存數(shù)據(jù)到本地緩存文件的代碼
BOOL isDir = NO;BOOL existed = [fm fileExistsAtPath:cacheDir isDirectory:&isDir];if (isDir == YES && existed == YES){[fm removeItemAtPath:cacheDir error:nil];}[fm createDirectoryAtPath:cacheDir withIntermediateDirectories:YES attributes:nil error:nil];[fm createFileAtPath:Json_path contents:nil attributes:nil];NSString *Json_path=[self.cacheDir stringByAppendingPathComponent:fileName];[[responseJsonDic JSONString]writeToFile:Json_path atomically:YES encoding:NSUTF8StringEncoding error:nil]; ??????首先檢查了文件是否存在,如果不存在則先創(chuàng)建,在使用[JSONKit writeToFile:atomically:encoding:error]方法來講Json數(shù)據(jù)寫到緩存文件。?????? 以下是從緩存文件中讀取數(shù)據(jù)的代碼
NSDictionary * JSON = [jsonStr objectFromJSONString]; NSDictionary * classMap = [[NSDictionary alloc]initWithObjectsAndKeys:NSStringFromClass(clazz),@"result", nil]; JsonBean * obj =[(NSDictionary *)JSON convertDicToObject:NSStringFromClass([JsonBean class]) classMap:classMap]; [self.dataArray addObjectsFromArray:obj.result];??????使用了第三方Json解析工具JSONKit,其中jsonStr是服務器數(shù)據(jù),classMap是從Json節(jié)點到實體類的映射。clazz是要轉換的實體類的class。
??????整理一下流程:
??????完整方法:
- (void) refreshTable {NSString * stringlev = [MyKeyChainHelper getUserLevelWithService:[MyKeyChainHelper getUserLevelKeyString]];NSInteger integerlev = [stringlev integerValue]<0?0:[stringlev integerValue];if (integerlev<self.spinner.grande_code) {UIAlertView * uv = [[UIAlertView alloc]initWithTitle:@"溫馨提示" message:@"對不起,您的訪問權限不足!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];[uv show];return;}if ([self.spinner.channelId isEqualToString:@"欄目指引"]) {[dataArray removeAllObjects];[dataArray addObject:@"欄目指引1"];[dataArray addObject:@"欄目指引2"];[dataArray addObject:@"欄目指引3"];[self refreshTableComplete];return;}isLastPage = NO;pageNumber=1;NSNumber *startIndex = [[NSNumber alloc]initWithInteger:1];NSString * fileName = [[NSString stringWithFormat:@"pageSize:%lu_startIndex:%@",(long)self.pageSize,startIndex]md5];NSString *Json_path=[self.cacheDir stringByAppendingPathComponent:fileName];BOOL fileExist = [fm fileExistsAtPath:Json_path];if (isFirstRefresh&&fileExist) {//isFirstRefresh表示初次載入界面,fileExist標示著緩存文件是否存在[pullTableDelegate startLoadData];NSError * error;NSString * jsonStr = [NSString stringWithContentsOfFile:Json_path encoding:NSUTF8StringEncoding error:&error];if (error) {}else{NSDictionary * JSON = [jsonStr objectFromJSONString];NSDictionary * classMap = [[NSDictionary alloc]initWithObjectsAndKeys:NSStringFromClass(clazz),@"result", nil];JsonBean * obj =[(NSDictionary *)JSON convertDicToObject:NSStringFromClass([JsonBean class]) classMap:classMap];[self.dataArray removeAllObjects];[self.dataArray addObjectsFromArray:obj.result];self.totalCount = obj.totalCount;if (self.totalCount<=self.pageSize) {isLastPage = YES;}//如果讀取到的數(shù)據(jù)長度為零,則顯示"欄目為空"提示頁面if([obj.result count] == 0) {[self addSubview:emptyView];}}[self refreshTableComplete];}else{if (![NetUtils isNetWorkConnected]) {[self refreshTableComplete];return;}if (isFirstRefresh) {[[CustomPopView shardInstance] show:@"reload" andMsg:@"數(shù)據(jù)加載中..." canAnimate:YES];[pullTableDelegate startLoadData];}[self.params setValue:startIndex forKey:@"startIndex"];[self.params setValue:[[NSNumber alloc]initWithInteger:self.pageSize] forKey:@"pageCount"];[HttpClient postWithBlock:self.url listClass:clazz params:self.params block:^(NSDictionary *responseJsonDic, NSError *error) {if (error) {} else {NSDictionary * classMap = [[NSDictionary alloc]initWithObjectsAndKeys:NSStringFromClass(clazz),@"result", nil];JsonBean * obj =[responseJsonDic convertDicToObject:NSStringFromClass([JsonBean class]) classMap:classMap];NSInteger code = obj.code;if (code==0) {[self.dataArray removeAllObjects];[self.dataArray addObjectsFromArray: [[NSMutableArray alloc]initWithArray:obj.result]];self.totalCount = obj.totalCount;if (self.totalCount<=self.pageSize) {isLastPage = YES;}//當欄目數(shù)據(jù)為空時,顯示提示頁面if([obj.result count] == 0) {[self addSubview:emptyView];[[CustomPopView shardInstance]hide];}else{BOOL isDir = NO;BOOL existed = [fm fileExistsAtPath:cacheDir isDirectory:&isDir];if (isDir == YES && existed == YES){[fm removeItemAtPath:cacheDir error:nil];}[fm createDirectoryAtPath:cacheDir withIntermediateDirectories:YES attributes:nil error:nil];[fm createFileAtPath:Json_path contents:nil attributes:nil];NSString *Json_path=[self.cacheDir stringByAppendingPathComponent:fileName];[[responseJsonDic JSONString]writeToFile:Json_path atomically:YES encoding:NSUTF8StringEncoding error:nil];}}else{UIAlertView * uv = [[UIAlertView alloc]initWithTitle:@"BaseTableViewCotroller_refreshTable_Error" message:obj.message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];[uv show];}}[self performSelector:@selector(refreshTableComplete) withObject:nil afterDelay:1];}];} } ??????本地緩存文件:
??????圖片數(shù)據(jù)的緩存:
??????圖片數(shù)據(jù)的緩存是通過一些第三方開源庫實現(xiàn)的,比如博主目前使用的SDWebImage,OSChina客戶端中使用的EGOImageLoading等。這些只需要耐心的看下文檔接口就好了。如果使用SDWebImage的話,目前博主使用的版本是不能在進行數(shù)據(jù)緩存之前進行緩存尺寸的設置的,為此博主寫了為SDImageView寫了一個簡單的Category,詳見:SDWebImage指定緩存圖片大小
??????用戶信息、程序信息等
??? 稍微扯一下,博主知道的保存這些數(shù)據(jù)的方法有UserDefault和KeyChain,KeyChain是加密過的,所以博主現(xiàn)在項目中保存用戶信息的是KeyChain,但是KeyChain是存在于系統(tǒng)中的,即卸載完程序后,并不會清除KeyChain數(shù)據(jù)。必須確保能夠在重新安裝時可以清空,那么博主的做法是結合UserDefault和KeyChain。在UserDefault中置一個變量用來表示程序是否為初次啟動。在程序啟動是加以判斷,如果是初次啟動的話,清除所有存在的KeyChain值。這樣就可以解決KeyChain的值在程序初次安裝時得以還原。
?????? O啦~~~
??????轉載請求保留出處:http://blog.csdn.net/u011638883/article/details/16979133
????? ?謝謝!!
?
轉載于:https://my.oschina.net/cjkall/blog/195810
總結
以上是生活随笔為你收集整理的OSChina_IOS版客户端笔记(四)_程序数据、缓存的管理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 六个月宝宝能吃什么 宝宝辅食添加要点
- 下一篇: OC中的几种延迟执行方式