iAronTalk Blog opens.
If you judge people, you have no time to love them.
-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
緩存占用了系統的大量空間,如何實時動態的顯示緩存的大小,使用戶清晰的了解緩存的積累情況,有效的進行一鍵清理呢?
為方便讀者和未來自己更好理解,我們創建這樣場景。(在表視圖的清除緩存一單元格內創建一個UILabel *cacheLabel用于顯示當前緩存,當點擊單元格彈出提示框,點擊確定,清除緩存)。

下面是實現代碼:
1 #PRagma mark - 計算緩存大小 2 - (NSString *)getCacheSize 3 { 4 //定義變量存儲總的緩存大小 5 long long sumSize = 0; 6 7 //01.獲取當前圖片緩存路徑 8 NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"]; 9 10 //02.創建文件管理對象11 NSFileManager *filemanager = [NSFileManager defaultManager];12 13 //獲取當前緩存路徑下的所有子路徑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).計算文件的大小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方法實現37 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex38 {39 NSLog(@"代碼執行到此");40 //判斷點擊的是確認鍵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僅做功能性展示,實時監測緩存大小,從其他界面跳轉到本頁面,也需要刷新下表視圖57 - (void)viewWillAppear:(BOOL)animated58 {59 [super viewWillAppear:YES];60 [_tableView reloadData];61 }
由于編者水平有限,不妥之處在所難免,懇請各個大牛批評指正,提出寶貴建議。
版權聲明:本文為博主原創文章,未經博主允許不得轉載。
新聞熱點
疑難解答