iOS-緩存大小顯示功能和一鍵清理功能

iOS-緩存大小顯示功能和一鍵清理功能

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 *)indexPath
30 {
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)buttonIndex
38 {
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)animated
58 {
59     [super viewWillAppear:YES];
60     [_tableView reloadData];
61 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章