NSFileManager,SDImageCache计算缓存,清除缓存

// 创建工具类 ClearnCache 继承NSobject

// .h 文件
#import <Foundation/Foundation.h>

@interface ClearnCache : NSObject

/**
 获取文件路劲

 @return 返回路径
 */
+ (NSString *)getCachesPath;

/**
 计算单个文件的大小

 @param filePath 路径
 @return 返回结果
 */
+ (long)fileSizeAtpath:(NSString *)filePath;

/**
 遍历文件夹获得文件夹大小
 */
+ (float)getCacheSizeAtPath;

/**
 清理缓存
 */
+ (void)clearCacheAtPath;



@end


// .m文件
#import "ClearnCache.h"

@implementation ClearnCache
/**
 获取路径
 */
+ (NSString *)getCachesPath
{
    // 获取caches目录路径
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    // 拼接路径
    NSString *filePath = [cachesPath stringByAppendingPathComponent:@"3D-Project"];
    // caches存放缓存,故不需要拼接
    return cachesPath;
}

+ (long)fileSizeAtpath:(NSString *)filePath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

+ (float)getCacheSizeAtPath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    // 判断文件路径是否存在
    if (![manager fileExistsAtPath:[ClearnCache getCachesPath]]) {
        return 0;
    }
    NSEnumerator *enumerator = [[manager subpathsAtPath:[ClearnCache getCachesPath]]objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [enumerator nextObject]) != nil) {
        NSString* fileAbsolutePath = [[ClearnCache getCachesPath] stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtpath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

+ (void)clearCacheAtPath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:[ClearnCache getCachesPath]]) {
        NSArray *chilederFiles = [manager subpathsAtPath:[ClearnCache getCachesPath]];
        for (NSString *fileName in chilederFiles) {
            NSString *absolutePath = [[ClearnCache getCachesPath] stringByAppendingPathComponent:fileName];
            [manager removeItemAtPath:absolutePath error:nil];
        }
    }
}

// 使用:
 
    // 计算缓存
    CGFloat size =[ClearnCache getCacheSizeAtPath];
    NSLog(@"Manage计算缓存:%f",size);
    // 清除缓存
    [ClearnCache clearCacheAtPath];


 

计算缓存

-(void)calculateCache{
    float cacheSize = 0;

   //SDImageCache 单利类,调用 getSize 方法
    NSInteger tmpSize = [[SDImageCache sharedImageCache] getSize];
    cacheSize = tmpSize / 1024.0 / 1024.0;
    _cacheLabel.text = [NSString stringWithFormat:@"%.2fMB",cacheSize];

}


清除缓存 

   [[SDImageCache sharedImageCache] clearDisk];

 

转载于:https://my.oschina.net/iOScoderZhao/blog/755275

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值