使用下面清除缓存的方法需要导入#import "SDImageCache.h"
//清除缓存的点击方法
- (void)clearBtnClicked:(UIButton *)sender
{
NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
//调用清除方法
[self clearCache:caches];
}
//清除缓存文件
- (void)clearCache:(NSString *)path{NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
NSArray *childerFiles=[fileManager subpathsAtPath:path];
for (NSString *fileName in childerFiles) {
//如有需要,加入条件,过滤掉不想删除的文件
NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
[fileManager removeItemAtPath:absolutePath error:nil];
}
}
[[SDImageCache sharedImageCache] cleanDisk];
}
- (long long)fileSizeAtPath:(NSString *)filePath{
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
//遍历文件夹获得文件夹大小,返回多少M
- (float)folderSizeAtPath:(NSString *)folderPath{
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:folderPath]) return 0;
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
NSString* fileName;
long long folderSize = 0;
while ((fileName = [childFilesEnumerator nextObject]) != nil){
NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeAtPath:fileAbsolutePath];
}
return folderSize/(1024.0*1024.0);
}
本文介绍如何在iOS应用中实现缓存清理功能,包括使用SDImageCache库进行缓存管理和提供清除缓存的用户界面操作。通过代码示例展示如何遍历文件夹、获取文件大小,并最终实现缓存的清除。

1003

被折叠的 条评论
为什么被折叠?



