iOS开发之1行代码实现缓存计算及清除缓存

2020-05-31 17:00:20 来源:易采站长站 作者:于丽

话不多说,直接撸代码

//
// gzhCache.h
// cache
//
// Created by 郭志贺 on 2020/5/27.
// Copyright © 2020 郭志贺. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface gzhCache : NSObject

/// 计算缓存大小
+(float)filePath;

/// 清理缓存
+(void)clearCache;
@end

NS_ASSUME_NONNULL_END
//
// gzhCache.m
// cache
//
// Created by 郭志贺 on 2020/5/27.
// Copyright © 2020 郭志贺. All rights reserved.
//

#import "gzhCache.h"

@implementation gzhCache
// 显示缓存大小
+ (float)filePath {
  NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];

  return [ self folderSizeAtPath :cachPath];
}
//计算单个文件的大小
+ (long long) fileSizeAtPath:( NSString *) filePath{
  NSFileManager * manager = [ NSFileManager defaultManager ];
  if ([manager fileExistsAtPath :filePath]){
    return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ];
  }
  return 0 ;
}
//遍历文件夹获得文件夹大小,返回多少M
+ (float)folderSizeAtPath:(NSString *)folderPath{
  NSFileManager * manager = [ NSFileManager defaultManager ];
  if (![manager fileExistsAtPath :folderPath]) return 0 ;
  NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
  NSString * fileName;
  long long folderSize = 0 ;
  while ((fileName = [childFilesEnumerator nextObject ]) != nil ){
    NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
    folderSize += [ self fileSizeAtPath :fileAbsolutePath];
  }
  return folderSize/( 1024.0 * 1024.0 );
}
//清理缓存
+ (void)clearCache {
  NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
  NSArray * files = [[ NSFileManager defaultManager ] subpathsAtPath :cachPath];
  NSLog ( @"cachpath = %@" , cachPath);
  for ( NSString * p in files) {
    NSError * error = nil ;
    NSString * path = [cachPath stringByAppendingPathComponent :p];
    if ([[ NSFileManager defaultManager ] fileExistsAtPath :path]) {
      [[ NSFileManager defaultManager ] removeItemAtPath :path error :&error];
    }
  }
  [ self performSelectorOnMainThread : @selector (clearCachSuccess) withObject : nil waitUntilDone : YES ];
}
+ (void)clearCachSuccess {
  NSLog(@"清理成功");
}
@end

需要查询大小的地方使用:

NSString *str = [NSString stringWithFormat:@"%.2fM",[gzhCache filePath]];

清理的方法调用

[gzhCache clearCache];

 以上内容仅代表本菜鸟看法,复制可直接使用。如有不妥之处敬请告知。

好了,到此这篇iOS开发之1行代码实现缓存计算及清除缓存的文章就介绍到这了,更多相关iOS缓存计算及清除缓存内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!

微信扫一扫

易采站长站微信账号