欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-28 16:28:37
话不多说,直接撸代码//// gzhcache.h// cache//// created by 郭志贺 on 2020/5/27.// copyright © 2020 郭志贺. all...

话不多说,直接撸代码

//
// 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缓存计算及清除缓存内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: ios 清除 缓存