1.首先,一般我們項(xiàng)目中的緩存一般分為2大塊,一個(gè)是自己緩存的一些數(shù)據(jù);還有一個(gè)就是我們使用的SDWebImage這個(gè)第三方庫(kù)給我們自動(dòng)緩存的圖片文件緩存了
<1>怎么計(jì)算緩存大小(主要是利用系統(tǒng)提供的NSFileManager類來(lái)實(shí)現(xiàn))
$1.單個(gè)文件大小的計(jì)算
1
2
3
4
5
6
7
8
|
-( long long )fileSizeAtPath:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:path]){ long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize; return size; } return 0; } |
$2.文件夾大小的計(jì)算(要利用上面的$1提供的方法)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
-( float )folderSizeAtPath:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; cachePath=[cachePath stringByAppendingPathComponent:path]; long long folderSize=0; if ([fileManager fileExistsAtPath:cachePath]) { NSArray *childerFiles=[fileManager subpathsAtPath:cachePath]; for (NSString *fileName in childerFiles) { NSString *fileAbsolutePath=[cachePath stringByAppendingPathComponent:fileName]; long long size=[self fileSizeAtPath:fileAbsolutePath]; folderSize += size; NSLog(@ "fileAbsolutePath=%@" ,fileAbsolutePath); } //SDWebImage框架自身計(jì)算緩存的實(shí)現(xiàn) folderSize+=[[SDImageCache sharedImageCache] getSize]; return folderSize/1024.0/1024.0; } return 0; } |
其中folderSize+=[[SDImageCache sharedImageCache] getSize];這行代碼是SDWebImage給我們提供的計(jì)算本地緩存圖片大小的方法....(當(dāng)然了,這個(gè)方法的底層實(shí)現(xiàn)依然是用的NSFileManager做的)
上面2個(gè)方法結(jié)合起來(lái)使用,就可以計(jì)算我們總共產(chǎn)生多少緩存啦....
2.計(jì)算好了緩存,那么怎么清除呢??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//同樣也是利用NSFileManager API進(jìn)行文件操作,SDWebImage框架自己實(shí)現(xiàn)了清理緩存操作,我們可以直接調(diào)用。 -( void )clearCache:(NSString *)path{ NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; cachePath=[cachePath stringByAppendingPathComponent:path]; NSFileManager *fileManager=[NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:cachePath]) { NSArray *childerFiles=[fileManager subpathsAtPath:cachePath]; for (NSString *fileName in childerFiles) { //如有需要,加入條件,過濾掉不想刪除的文件 NSString *fileAbsolutePath=[cachePath stringByAppendingPathComponent:fileName]; NSLog(@ "fileAbsolutePath=%@" ,fileAbsolutePath); [fileManager removeItemAtPath:fileAbsolutePath error:nil]; } } [[SDImageCache sharedImageCache] cleanDisk]; } |
上面再清楚換存的時(shí)候也清除了2塊地方,一個(gè)是我們自己緩存的文件夾;還有就是SDWebImage給我們緩存的圖片文件....
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.jianshu.com/p/ae1a3979292b?utm_source=tuicool&utm_medium=referral