iOS 计算缓存大小
2017-05-02 本文已影响0人
低调的前行者灬
1.计算Cache文件夹大小,包括了SDWebImage的图片缓存
//根据路径获取大小
-(CGFloat)getCacheNumWithPath:(NSString *)path
{
NSFileManager *manager = [NSFileManager defaultManager];
CGFloat size = 0;
if ([manager fileExistsAtPath:path]) {
// 目录下的文件计算大小
NSArray *childrenFile = [manager subpathsAtPath:path];
for (NSString *fileName in childrenFile) {
NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
size += [manager attributesOfItemAtPath:absolutePath error:nil].fileSize;
}
//SDWebImage的缓存计算
size += [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
// 将大小转化为M
return size / 1024.0 / 1024.0;
}
return 0;
}
2.计算数据库的大小
//获取
NSString *douPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *dbPath = [douPath stringByAppendingPathComponent:@"haha.db"];
CGFloat dbSize = [[NSFileManager defaultManager] attributesOfItemAtPath:dbPath error:nil].fileSize/ 1024.0 / 1024.0;
DLog(@"数据库大小--%f",[[NSFileManager defaultManager] attributesOfItemAtPath:dbPath error:nil].fileSize/ 1024.0 / 1024.0);
3.#清除缓存
//清除缓存
-(void)clearAnyeLocalCache
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES);
NSString *path = [paths lastObject];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
NSArray *childrenFiles = [fileManager subpathsAtPath:path];
for (NSString *fileName in childrenFiles) {
// 拼接路径
NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
// 将文件删除
[fileManager removeItemAtPath:absolutePath error:nil];
}
}
//SDWebImage的清除功能
[[SDImageCache sharedImageCache] clearDisk];
[[SDImageCache sharedImageCache] clearMemory];
//删除数据库缓存
NSString *douPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *dbPath = [douPath stringByAppendingPathComponent:@"haha.db"];
NSError *error;
[fileManager removeItemAtPath:dbPath error:&error];
if (error == nil) {
[[AnyeDataManager sharedManager] dataBaseDealloc];
DLog(@"删除数据库成功");
}else{
DLog(@"删除数据库失败");
}
}