iOS中的缓存计算和清除完整实例代码
1.首先,一般我们项目中的缓存一般分为2大块,一个是自己缓存的一些数据;还有一个就是我们使用的SDWebImage这个第三方库给我们自动缓存的图片文件缓存了
<1>怎么计算缓存大小(主要是利用系统提供的NSFileManager类来实现)
$1.单个文件大小的计算
-(longlong)fileSizeAtPath:(NSString*)path{
NSFileManager*fileManager=[NSFileManagerdefaultManager];
if([fileManagerfileExistsAtPath:path]){
longlongsize=[fileManagerattributesOfItemAtPath:patherror:nil].fileSize;
returnsize;
}
return0;
}
$2.文件夹大小的计算(要利用上面的$1提供的方法)
-(float)folderSizeAtPath:(NSString*)path{
NSFileManager*fileManager=[NSFileManagerdefaultManager];
NSString*cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
cachePath=[cachePathstringByAppendingPathComponent:path];
longlongfolderSize=0;
if([fileManagerfileExistsAtPath:cachePath])
{
NSArray*childerFiles=[fileManagersubpathsAtPath:cachePath];
for(NSString*fileNameinchilderFiles)
{
NSString*fileAbsolutePath=[cachePathstringByAppendingPathComponent:fileName];
longlongsize=[selffileSizeAtPath:fileAbsolutePath];
folderSize+=size;
NSLog(@"fileAbsolutePath=%@",fileAbsolutePath);
}
//SDWebImage框架自身计算缓存的实现
folderSize+=[[SDImageCachesharedImageCache]getSize];
returnfolderSize/1024.0/1024.0;
}
return0;
}
其中folderSize+=[[SDImageCachesharedImageCache]getSize];这行代码是SDWebImage给我们提供的计算本地缓存图片大小的方法....(当然了,这个方法的底层实现依然是用的NSFileManager做的)
上面2个方法结合起来使用,就可以计算我们总共产生多少缓存啦....
2.计算好了缓存,那么怎么清除呢??
//同样也是利用NSFileManagerAPI进行文件操作,SDWebImage框架自己实现了清理缓存操作,我们可以直接调用。
-(void)clearCache:(NSString*)path{
NSString*cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
cachePath=[cachePathstringByAppendingPathComponent:path];
NSFileManager*fileManager=[NSFileManagerdefaultManager];
if([fileManagerfileExistsAtPath:cachePath]){
NSArray*childerFiles=[fileManagersubpathsAtPath:cachePath];
for(NSString*fileNameinchilderFiles){
//如有需要,加入条件,过滤掉不想删除的文件
NSString*fileAbsolutePath=[cachePathstringByAppendingPathComponent:fileName];
NSLog(@"fileAbsolutePath=%@",fileAbsolutePath);
[fileManagerremoveItemAtPath:fileAbsolutePatherror:nil];
}
}
[[SDImageCachesharedImageCache]cleanDisk];
}
上面再清楚换存的时候也清除了2块地方,一个是我们自己缓存的文件夹;还有就是SDWebImage给我们缓存的图片文件....
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。