ios 清空缓存方法

#pragma mark === 暂时不用清除缓存=====

-(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]);

                       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

{

    NSLog(@"清理成功");

}

 

 

 

//获取缓存大小。。

CGFloat fileSize = [self folderSizeAtPath:cachePath];

        

        dispatch_async(dispatch_get_main_queue(), ^{

            cache.subtitle = [NSString stringWithFormat:@"%.2fMB",fileSize];

            [self.tableView reloadData];

 

        });

 

 

- (CGFloat)folderSizeAtPath:(NSString *)folderPath

{

    NSFileManager *manager = [NSFileManagerdefaultManager];

    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 = [NSFileManagerdefaultManager];

    if ([manager fileExistsAtPath:filePath]){

        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];

    }

    return 0;

 

}

猜你喜欢

转载自zhangmingwei.iteye.com/blog/2049196