移动应用在处理网络资源时,一般都会做离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为SDWebImage,另外应用也有其他缓存,比如数据库缓存、文件缓存等等。下面我们讲一下图片缓存和文件缓存的清理方式:
一、图片缓存-SDWebImage:
SDWebImage提供了很简单的获取和清空的接口,直接使用就可以了
获取图片缓存数量:
float fCacheSize = [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0; cell.detailTextLabel.text = [NSString stringWithFormat:@"%.1fM", fCacheSize];清理图片缓存:
[self showProgressHUD]; [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{ [self hideProgressHUD]; [self.view makeToast:@"清除完成" duration:0.5 position:CSToastPositionCenter]; [self.tableView reloadData]; }];二、文件缓存:
获取文件缓存:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) NSString *path = [paths lastObject]; float fCacheSize = [self folderSizeAtPath:path];
#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; } -(float)folderSizeAtPath:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; float folderSize; if ([fileManager fileExistsAtPath:path]) { NSArray *childerFiles=[fileManager subpathsAtPath:path]; for (NSString *fileName in childerFiles) { NSString *absolutePath=[path stringByAppendingPathComponent:fileName]; folderSize +=[self fileSizeAtPath:absolutePath]; } //SDWebImage框架自身计算缓存的实现 folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0; return folderSize; } return 0; } -(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]; }清理缓存:
[self showProgressHUD]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,NULL), ^{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *path = [paths lastObject]; [self clearCache:path]; dispatch_async(dispatch_get_main_queue(), ^{ [self hideProgressHUD]; [self.view makeToast:@"清除完成" duration:0.5 position:CSToastPositionCenter]; [self.tableView reloadData]; }); });