清除缓存

2017-10-17  本文已影响14人  Coder007

计算缓存大小

如何计算缓存大小
NSFileManager *manager = [NSFileManager defaultManager];
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *cachePath = [caches stringByAppendingPathComponent:@"default/com.hackemist.SDWebImageCache.default"];
// 遍历器
NSDirectoryEnumerator *fileEnumerator = [manager enumeratorAtPath:cachePath];
NSInteger totalSize = 0;
[[SDImageCache sharedImageCache] getSize];
for (NSString *fileName in fileEnumerator) {
    // 拼接文件的全路径,有可能是文件,有可能是文件夹
    NSString *filePath = [cachePath stringByAppendingPathComponent:fileName];
    NSDictionary *attrs = [manager attributesOfItemAtPath:filePath error:nil];
    // 排除是文件夹,不计算文件夹的大小
    if([attrs[NSFileType] isEqualToString:NSFileTypeDirectory]) continue;
    totalSize += [attrs[NSFileSize] integerValue];
}
NSFileManager *manager = [NSFileManager defaultManager];
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *cachePath = [caches stringByAppendingPathComponent:@"default/com.hackemist.SDWebImageCache.default"];
// 获取当前路径下所有子路径(包含所有文件夹和文件)
NSArray *subpaths = [manager subpathsOfDirectoryAtPath:cachePath error:nil];
NSInteger totalSize = 0;
for (NSString *fileName in subpaths) {
    // 拼接文件的全路径,有可能是文件,有可能是文件夹
    NSString *filePath = [cachePath stringByAppendingPathComponent:fileName];
    NSDictionary *attrs = [manager attributesOfItemAtPath:filePath error:nil];
    if([attrs[NSFileType] isEqualToString:NSFileTypeDirectory]) continue;
    totalSize += [attrs[NSFileSize] integerValue];
}

删除缓存文件

NSFileManager *manager = [NSFileManager defaultManager];
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *cachePath = [caches stringByAppendingPathComponent:@"default/com.hackemist.SDWebImageCache.default"];
[manager removeItemAtPath:cachePath error:nil];
上一篇 下一篇

猜你喜欢

热点阅读