- 只需要清理SDWebImage的圖片緩存,直接用SDImageCache單例的getSize方法
// 字節(jié)大小
NSInteger byteSize = [SDImageCache sharedImageCache].getSize;
// M大小 蘋果電腦計算不是1024
double size = byteSize / 1000.0 / 1000.0;
NSString *cacheSize = [NSString stringWithFormat:@"緩存大小(%.1fM)", size];
/**
* 計算當前文件\文件夾的內容大小
*/
- (void)clearCache
{
// 提醒
UIActivityIndicatorView *circle = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[circle startAnimating];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:circle];
// 清除緩存
[[SDImageCache sharedImageCache] clearDisk];
// 顯示按鈕
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"清除緩存" style:0 target:self action:@selector(clearCache)];
self.navigationItem.title = [NSString stringWithFormat:@"緩存大小(0M)"];
}
2.除了圖片還有其他緩存文件就需要刪除Library/Cache文件夾,搞一個NSString分類,給一個獲取文件夾、文件的所有大小的方法
- (NSInteger)fileSize
{
NSFileManager *mgr = [NSFileManager defaultManager];
// 判斷是否為文件
BOOL dir = NO;
BOOL exists = [mgr fileExistsAtPath:self isDirectory:&dir];
// 文件\文件夾不存在
if (exists == NO) return 0;
if (dir) { // self是一個文件夾
// 遍歷caches里面的所有內容 --- 直接和間接內容
NSArray *subpaths = [mgr subpathsAtPath:self];
NSInteger totalByteSize = 0;
for (NSString *subpath in subpaths) {
// 獲得全路徑
NSString *fullSubpath = [self stringByAppendingPathComponent:subpath];
// 判斷是否為文件
BOOL dir = NO;
[mgr fileExistsAtPath:fullSubpath isDirectory:&dir];
if (dir == NO) { // 文件
totalByteSize += [[mgr attributesOfItemAtPath:fullSubpath error:nil][NSFileSize] integerValue];
}
}
return totalByteSize;
} else { // self是一個文件
return [[mgr attributesOfItemAtPath:self error:nil][NSFileSize] integerValue];
}
}
使用分類計算大小,直接刪除cache文件夾
- (void)fileOperation
{
// 文件管理者
NSFileManager *mgr = [NSFileManager defaultManager];
// 緩存路徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//文件大小
NSInteger cacheSize = [caches fileSize];
NSLog(@"%zd",cacheSize);
// 刪除文件夾
[mgr removeItemAtPath:caches error:nil];
}