iOS

iOS 一句话调用清除缓存

学习笔记

Posted by Asingers on January 19, 2017
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#import <Foundation/Foundation.h>
typedef void(^cleanCacheBlock)();

@interface YJCleanCache : NSObject
/**
 *  清理缓存
 */
+(void)cleanCache:(cleanCacheBlock)block;

/**
 *  整个缓存目录的大小
 */
+(float)folderSizeAtPath;
@end

#import "YJCleanCache.h"

@implementation YJCleanCache
/**
 *  清理缓存
 */
+(void)cleanCache:(cleanCacheBlock)block
{
		dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
				//文件路径
				NSString *directoryPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

				NSArray *subpaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil];

				for (NSString *subPath in subpaths) {
						NSString *filePath = [directoryPath stringByAppendingPathComponent:subPath];
						[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
				}
				//返回主线程
				dispatch_async(dispatch_get_main_queue(), ^{
						block();
				});
		});

}
/**
 *  计算整个目录大小
 */
+(float)folderSizeAtPath
{
		NSString *folderPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

		NSFileManager * manager=[NSFileManager defaultManager ];
		if (![manager fileExistsAtPath :folderPath]) {
				return 0 ;
		}
		NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
		NSString * fileName;
		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 ;

}

@end

[YJCleanCache folderSizeAtPath];
文章使用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议