iAronTalk Blog opens.
If you judge people, you have no time to love them.
-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
緩存占用了系統(tǒng)的大量空間,如何實(shí)時動態(tài)的顯示緩存的大小,使用戶清晰的了解緩存的積累情況,有效的進(jìn)行一鍵清理呢?
為方便讀者和未來自己更好理解,我們創(chuàng)建這樣場景。(在表視圖的清除緩存一單元格內(nèi)創(chuàng)建一個UILabel *cacheLabel用于顯示當(dāng)前緩存,當(dāng)點(diǎn)擊單元格彈出提示框,點(diǎn)擊確定,清除緩存)。
下面是實(shí)現(xiàn)代碼:
1 #PRagma mark - 計(jì)算緩存大小 2 - (NSString *)getCacheSize 3 { 4 //定義變量存儲總的緩存大小 5 long long sumSize = 0; 6 7 //01.獲取當(dāng)前圖片緩存路徑 8 NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"]; 9 10 //02.創(chuàng)建文件管理對象11 NSFileManager *filemanager = [NSFileManager defaultManager];12 13 //獲取當(dāng)前緩存路徑下的所有子路徑14 NSArray *subPaths = [filemanager subpathsOfDirectoryAtPath:cacheFilePath error:nil];
15 //遍歷所有子文件16 for (NSString *subPath in subPaths) {17 //1).拼接完整路徑18 NSString *filePath = [cacheFilePath stringByAppendingFormat:@"/%@",subPath];19 //2).計(jì)算文件的大小20 long long fileSize = [[filemanager attributesOfItemAtPath:filePath error:nil]fileSize];21 //3).加載到文件的大小22 sumSize += fileSize;23 }24 float size_m = sumSize/(1000*1000);25 return [NSString stringWithFormat:@"%.2fM",size_m];26 27 }28 #pragma mark - 清除緩存提示(UITableViewDataSourceDelegate)29 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath30 {31 if (indexPath.row == 0) {32 UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"緩存清除" message:@"確定清除緩存?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定",nil];33 [alertView show];34 }35 }36 #pragma mark - UIAlertViewDelegate方法實(shí)現(xiàn)37 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex38 {39 NSLog(@"代碼執(zhí)行到此");40 //判斷點(diǎn)擊的是確認(rèn)鍵41 if (buttonIndex == 1) {42 //01......43 NSFileManager *fileManager = [NSFileManager defaultManager];44 //02.....45 NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];46 //03......47 [fileManager removeItemAtPath:cacheFilePath error:nil];48 49 //04刷新第一行單元格50 NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];51 [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];52 53 //05 :04和05使用其一即可54 [_tableView reloadData];//刷新表視圖55 }56 @pragma -mark -放置于.m文件首段較為合適,本DEMO僅做功能性展示,實(shí)時監(jiān)測緩存大小,從其他界面跳轉(zhuǎn)到本頁面,也需要刷新下表視圖57 - (void)viewWillAppear:(BOOL)animated58 {59 [super viewWillAppear:YES];60 [_tableView reloadData];61 }
由于編者水平有限,不妥之處在所難免,懇請各個大牛批評指正,提出寶貴建議。
版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。
新聞熱點(diǎn)
疑難解答
圖片精選