IOS-计算缓存大小与清空缓存

2017-05-11  本文已影响59人  高谈阔论

//获取路径

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

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

//计算缓存中所有文件大小

double sizeBig = 0;

for (NSString *p in files)

{

NSError *error;

NSString *path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];

NSFileManager *fileManager=[NSFileManager defaultManager];

if([fileManager fileExistsAtPath:path]){

long long size=[fileManager attributesOfItemAtPath:path error:error].fileSize;

sizeBig += size/1024.0/1024.0;

}

}

NSLog(@"%fM",sizeBig);

//执行清理

for (NSString *p in files)

{

NSError *error;

NSString *path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];

//清理缓存

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

{

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

}

}

上一篇下一篇

猜你喜欢

热点阅读