在删除之前我们需要显示缓存的大小,提示一下当前缓存是否需要清空:
计算缓存大小的方法如下:
[cpp]
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"/Three20/"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
NSEnumerator *childEnumber = [[fileManager subpathsOfDirectoryAtPath:path error:nil] objectEnumerator];
unsigned long long folderSize = 0;
NSString *fileName;
while ((fileName = [childEnumber nextObject]) != nil) {
NSString *childFilePath = [path stringByAppendingPathComponent:fileName];
folderSize += [fileManager attributesOfItemAtPath:childFilePath error:nil].fileSize;
}
dispatch_async(dispatch_get_main_queue(), ^(void){
clearCacheButton.text = [NSString stringWithFormat:@"清空图片缓存( %0.1f Mb)", (float)folderSize/1000/1000];
[self reloadTableCells];
});
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"/Three20/"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
NSEnumerator *childEnumber = [[fileManager subpathsOfDirectoryAtPath:path error:nil] objectEnumerator];
unsigned long long folderSize = 0;
NSString *fileName;
while ((fileName = [childEnumber nextObject]) != nil) {
NSString *childFilePath = [path stringByAppendingPathComponent:fileName];
folderSize += [fileManager attributesOfItemAtPath:childFilePath error:nil].fileSize;
}
dispatch_async(dispatch_get_main_queue(), ^(void){
clearCacheButton.text = [NSString stringWithFormat:@"清空图片缓存( %0.1f Mb)", (float)folderSize/1000/1000];
[self reloadTableCells];
});
}
});
GCD的使用请参考:iOS多线程
编程之Grand Central Dispatch(GCD)介绍和使用
主要是缓存文件过多时计算文件大小需要一定的时间。
清空缓存的方法:
[cpp]
[[TTURLCache sharedCache] removeAll:YES];
[[TTURLCache sharedCache] removeAll:YES];