//获取路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// 计算文件夹所有问价所占的空间
CGFloat size = [self caculateFileCapacityAtPath:path];
// 移除所有的缓存
[self removeFileAtPath:path];
计算文件夹大小
-(CGFloat)caculateFileCapacityAtPath:(NSString *)path{
//获取所有文件的大小
CGFloat totalsize = 0.0 ;
NSFileManager *filemanage = [NSFileManager defaultManager];
if ([filemanage fileExistsAtPath:path]) {
NSArray *subpaths = [filemanage subpathsAtPath:path];
NSEnumerator *enuerr = [subpaths objectEnumerator];
NSString *subfilepath ;
while (subfilepath = [enuerr nextObject]) {
NSString *filepath = [path stringByAppendingPathComponent:subfilepath];
NSDictionary *dic = [filemanage attributesOfItemAtPath:filepath error:nil];
if (dic) {
CGFloat filesize = [[dic objectForKey:@"NSFileSize"] floatValue];
totalsize += filesize ;
}else{
NSLog(@"属性不存在");
}
}
// 返回单位为 M
return totalsize/(1024.0 * 1024.0) ;
}else{
return 0.0 ;
}
}
清除文件夹下的内容
/* 清除该路径下所有的文件以及文件夹 */
-(void)removeFileAtPath:(NSString *)path{
NSFileManager *filemanage = [NSFileManager defaultManager];
if ([filemanage fileExistsAtPath:path]) {
// 找出该文件夹下所有文件所在的子路径
NSArray *subpaths = [filemanage subpathsAtPath:path];
/* NSEnumerator 用于快速遍历subpaths中的元素 */
NSEnumerator *enumerr = [subpaths objectEnumerator];
/* 遍历至最后一个对象之后 返回值为空 */
NSString *subpath ;
while (subpath = [enumerr nextObject]) {
NSString *filepath = [path stringByAppendingPathComponent:subpath];
[filemanage removeItemAtPath:filepath error:nil];
}
}else{
NSLog(@"该文件夹不存在");
}
}
网友评论