iOS清除缓存

 

[objc] view plaincopy
 
  1. #pragma mark === 暂时不用清除缓存=====  
  2. -(void)myClearCacheAction{  
  3.     dispatch_async(  
  4.                    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)  
  5.                    , ^{  
  6.                        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];  
  7.                          
  8.                        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];  
  9.                        NSLog(@"files :%lu",(unsigned long)[files count]);  
  10.                        for (NSString *p in files) {  
  11.                            NSError *error;  
  12.                            NSString *path = [cachPath stringByAppendingPathComponent:p];  
  13.                            if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {  
  14.                                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];  
  15.                            }  
  16.                        }  
  17.                        [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});  
  18. }  
  19.    
  20.    
  21. -(void)clearCacheSuccess  
  22. {  
  23.     NSLog(@"清理成功");  
  24.    
  25. }  
  26.    
  27.    
  28.    
  29. //获取缓存大小。。  
  30. CGFloat fileSize = [self folderSizeAtPath:cachePath];  
  31.           
  32.         dispatch_async(dispatch_get_main_queue(), ^{  
  33.             cache.subtitle = [NSString stringWithFormat:@"%.2fMB",fileSize];  
  34.             [self.tableView reloadData];  
  35.    
  36.         });  
  37.    
  38.    
  39. - (CGFloat)folderSizeAtPath:(NSString *)folderPath  
  40. {  
  41.     NSFileManager *manager = [NSFileManagerdefaultManager];  
  42.     if (![manager fileExistsAtPath:folderPath]) {  
  43.         return 0;  
  44.     }  
  45.       
  46.     NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];  
  47.       
  48.     NSString *fileName = nil;  
  49.     long long folderSize = 0;  
  50.     while ((fileName = [childFilesEnumerator nextObject]) != nil) {  
  51.         NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];  
  52.         folderSize += [self fileSizeAtPath:fileAbsolutePath];  
  53.     }  
  54.     return folderSize/(1024.0*1024.0);  
  55. }  
  56.    
  57. - (long long)fileSizeAtPath:(NSString *)filePath  
  58. {  
  59.     NSFileManager* manager = [NSFileManagerdefaultManager];  
  60.     if ([manager fileExistsAtPath:filePath]){  
  61.         return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];  
  62.     }  
  63.     return 0;  
  64.    
  65. }  

posted on 2015-12-29 22:08  konglei  阅读(553)  评论(0编辑  收藏  举报

导航