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

iOS清除所有缓存的实例代码

程序员文章站 2023-12-18 20:33:04
 本文介绍了ios清除所有缓存的实例代码,分享给大家,具体如下: 计算缓存 nsstring *libpath = nssearchpathfordi...

 本文介绍了ios清除所有缓存的实例代码,分享给大家,具体如下:

计算缓存

nsstring *libpath = nssearchpathfordirectoriesindomains(nslibrarydirectory, nsuserdomainmask, yes)[0];
cgfloat filesize=[self foldersizeatpath:libpath];
- (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);
}
- (long long)filesizeatpath:(nsstring*) filepath{
  nsfilemanager* manager = [nsfilemanager defaultmanager];
  if ([manager fileexistsatpath:filepath]){
    return [[manager attributesofitematpath:filepath error:nil] filesize];
  }
  return 0;
}

清除缓存

- (void)action:(id)sender
{
  nsarray *paths = nssearchpathfordirectoriesindomains(nslibrarydirectory, nsuserdomainmask, yes);
  nsstring *path = [paths lastobject];

  nsarray *files = [[nsfilemanager defaultmanager] subpathsatpath:path];

  for (nsstring *p in files) {
    nserror *error;
    nsstring *path = [path stringbyappendingpathcomponent:p];
    if ([[nsfilemanager defaultmanager] fileexistsatpath:path]) {
      //清理缓存,保留preference,里面含有nsuserdefaults保存的信息
      if (![path containsstring:@"preferences"]) {
        [[nsfilemanager defaultmanager] removeitematpath:path error:&error];
      }
    }else{

    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: