您的位置:首页 > 移动开发 > IOS开发

ios开发计算缓存的大小以及清除

2016-02-22 21:10 405 查看
-(void)myClearCacheAction{

 
 
dispatch_async(

    
     
     
 
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

    
     
     
  , ^{


    
     
     
     

NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,
YES)
objectAtIndex:0];

 
     
     
     
   


    
     
     
     

NSArray *files =
[[
NSFileManager
defaultManager] subpathsAtPath:cachPath];

    
     
     
     

NSLog(@"files
:%lu"
,(unsigned long)[files
count]);

 
     
     
     
   


    
     
     
     

NSLog(@"缓存路径------------------%@",self.cachPath);

    
     
     
     

for (NSString
*p in
files) {

    
     
     
     
   
NSError *error;

    
     
     
     
   
NSString *path =
[cachPath
stringByAppendingPathComponent:p];

    
     
     
     
   
if ([[NSFileManager
defaultManager] fileExistsAtPath:path])
{


    
     
     
     
     
  [[
NSFileManager defaultManager]
removeItemAtPath:path error:&error];

    
     
     
     
    }


    
     
     
     
}


    
     
     
     
[
self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});

}

//清理缓存

-(void)clearCacheSuccess

{

 
 
UIAlertController *alert =
[
UIAlertController
alertControllerWithTitle:@"提示"
message:@"清理缓存成功"
preferredStyle: UIAlertControllerStyleAlert];

  
 


  
 


  
 


 
  [alert
addAction:[UIAlertAction
actionWithTitle:@"确定"
style:UIAlertActionStyleDefault handler:^(UIAlertAction
* _Nonnull action)
{


    
   


    
   


 
  }]];


  
 


 
 
//弹出提示框;

 
  [
self
presentViewController:alert animated:true
completion:nil];

  
 


  
 


}

//计算缓存大小

- (CGFloat)folderSizeAtPath:(NSString *)folderPath

{

 
 
NSFileManager *manager =
[
NSFileManager
defaultManager];

 
 
if
(![manager fileExistsAtPath:folderPath]) {

 
     

return 0;

 
  }


  
 


 
 
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];

  
 


 
 
NSString *fileName
=
nil;

 
 
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;

  
 


}

$(".MathJax").remove();
<
4000
/script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: