緩衝佔用了系統的大量空間,如何即時動態顯示緩衝的大小,使使用者清晰的瞭解緩衝的積累情況,有效進行一鍵清理呢?
為方便讀者和未來自己更好理解,我們建立這樣情境。(在表視圖的清除緩衝一儲存格內建立一個UILabel *cacheLabel用於顯示當前緩衝,當點擊儲存格彈出提示框,點擊確定,清除緩衝)。
下面是實現代碼:
#pragma mark - 計算緩衝大小- (NSString *)getCacheSize{//定義變數儲存總的緩衝大小long long sumSize = 0;//01.擷取當前圖片緩衝路徑NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];//02.建立檔案管理對象NSFileManager *filemanager = [NSFileManager defaultManager];//擷取當前緩衝路徑下的所有子路徑NSArray *subPaths = [filemanager subpathsOfDirectoryAtPath:cacheFilePath error:nil];//遍曆所有子檔案for (NSString *subPath in subPaths) {//1).拼接完整路徑NSString *filePath = [cacheFilePath stringByAppendingFormat:@"/%@",subPath];//2).計算檔案的大小long long fileSize = [[filemanager attributesOfItemAtPath:filePath error:nil]fileSize];//3).載入到檔案的大小sumSize += fileSize;}float size_m = sumSize/(1000*1000);return [NSString stringWithFormat:@"%.2fM",size_m];}#pragma mark - 清除緩衝提示(UITableViewDataSourceDelegate)- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{if (indexPath.row == 0) {UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"緩衝清除" message:@"確定清除緩衝?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定",nil];[alertView show];}}#pragma mark - UIAlertViewDelegate方法實現- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{NSLog(@"代碼執行到此");//判斷點擊的是確認鍵if (buttonIndex == 1) {//01......NSFileManager *fileManager = [NSFileManager defaultManager];//02.....NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];//03......[fileManager removeItemAtPath:cacheFilePath error:nil];//04重新整理第一行儲存格NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];[_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];//05 :04和05使用其一即可[_tableView reloadData];//重新整理表視圖}@pragma -mark -放置於.m檔案首段較為合適,本DEMO僅做功能性展示,即時監測緩衝大小,從其他介面跳轉到本頁面,也需要重新整理下表視圖- (void)viewWillAppear:(BOOL)animated{[super viewWillAppear:YES];[_tableView reloadData];}
以上所述是小編給大家介紹的iOS快取檔案大小顯示功能和一鍵清理功能的實現方法,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!