一、一般Xcode的緩存分為兩大塊:
一是自己工程緩存的一些數(shù)據(jù);第二如果使用了SDWebImage則還需要清理圖片緩存。
二、計(jì)算單個(gè)文件的大小
-(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;
}
三、計(jì)算文件夾的大小(含SDWenImage的圖片緩存)
-(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;
}
四、得到了緩存大小最后就是清除緩存了
//同樣也是利用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) {
//如有需要,加入條件,過(guò)濾掉不想刪除的文件
NSString *fileAbsolutePath=[cachePath stringByAppendingPathComponent:fileName];
NSLog(@"fileAbsolutePath=%@",fileAbsolutePath);
[fileManager removeItemAtPath:fileAbsolutePath error:nil];
}
}
[[SDImageCache sharedImageCache] cleanDisk];
}
五、個(gè)人經(jīng)驗(yàn)總結(jié)(坑)
1.做緩存清理最好封裝一個(gè)單例管理對(duì)象,對(duì)象要保證唯一性;
2.緩存路徑可以封裝一下,這樣在外面調(diào)用的時(shí)候就可以不用再傳路徑了;
3.清理的過(guò)程涉及到遍歷子路徑,當(dāng)緩存多的時(shí)候,會(huì)有很長(zhǎng)的耗時(shí)操作,所以這時(shí)應(yīng)該講遍歷刪除的過(guò)程全部寫(xiě)到新開(kāi)辟的子線程中去,然后回到主線程刷新UI界面;
六、完了。