1,计算缓存
-(void)caculateCacheSize{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
_cacheStr = [NSString stringWithFormat:@"%.2fMB",[self folderSizeAtPath]];
if (_cacheStr.length) {
dispatch_sync_on_main_queue(^{
[self.myTableView reloadData];
});
}
});
}
#pragma mark 计算目录大小
- (float)folderSizeAtPath{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSFileManager *fileManager=[NSFileManager defaultManager];
float folderSize = 0;
if ([fileManager fileExistsAtPath: path]) {
NSArray *childerFiles =[fileManager subpathsAtPath: path];
for (NSString *fileName in childerFiles) {
NSString *absolutePath=[path stringByAppendingPathComponent: fileName];
folderSize +=[self fileSizeAtPath: absolutePath];
}
folderSize+=[YYImageCache sharedCache].diskCache.totalCost/1024.0/1024.0;
return fabsf(folderSize);
}
return 0;
}
#pragma mark 计算单个文件的大小
- (float)fileSizeAtPath:(NSString *)path{
NSFileManager *fileManager=[NSFileManager defaultManager];
if([fileManager fileExistsAtPath: path]){
long long size=[fileManager attributesOfItemAtPath: path error: nil].fileSize;
return size/1024.0/1024.0;
}
return 0;
}
2,执行清除缓存操作:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
for (NSString *p in files)
{
NSError *error;
NSString *path = [cachPath stringByAppendingPathComponent:p];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
[[NSFileManager defaultManager] removeItemAtPath:path error:&error];
}
}
[[YYImageCache sharedCache].diskCache removeAllObjects];
网友评论