iOS缓存清理思路的实现

首先在讲缓存清理之前讲讲文件管理的几个知识点             

                                           第一部分 文件管理几个常用的方法

一 比较两个文件的内容是否一样

/* -contentsEqualAtPath:andPath: does not take into account data stored in the resource fork or filesystem extended attributes.

 */

- (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2;


二 路径中的文件是否存在

/* The following methods are of limited utility. Attempting to predicate behavior based on the current state of the filesystem or a particular file on the filesystem is encouraging odd behavior in the face of filesystem race conditions. It's far better to attempt an operation (like loading a file or creating a directory) and handle the error gracefully than it is to try to figure out ahead of time whether the operation will succeed.

 */

- (BOOL)fileExistsAtPath:(NSString *)path;


三 移除路径中文件内容

/* These methods replace their non-error returning counterparts below. See the NSFileManagerDelegate protocol below for methods that are dispatched to the NSFileManager instance's delegate.

 */

- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error


四 从一个文件中读取数据

/* These methods are provided here for compatibility. The corresponding methods on NSData which return NSErrors should be regarded as the primary method of creating a file from an NSData or retrieving the contents of a file as an NSData.

 */

- (NSData *)contentsAtPath:(NSString *)path;



五 从缓存路径中取出缓存文件内容,该返回值是数组,用数组接收即可


/* subpathsAtPath: returns an NSArray of all contents and subpaths recursively from the provided path. This may be very expensive to compute for deep filesystem hierarchies, and should probably be avoided.

 */

- (NSArray *)subpathsAtPath:(NSString *)path;



六 根据文件名拼接路径

- (NSString *)stringByAppendingPathComponent:(NSString *)str;




七 根据路径计算路径中文件的大小


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



                           第二部分  缓存清理思路的文字描述


第一步 拿到需要清理的缓存文件路径


 NSString* filePath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];


第二步 创建文件管理者


 NSFileManager *fileManager=[NSFileManager defaultManager];

 

第三步 判断缓存文件路径中的文件内容是否存在


if ([fileManager fileExistsAtPath:path])

第四步 遍历缓存路径,拿到路径中所有文件数组

NSArray *childerFiles = [fileManager subpathsAtPath:path];

第五步  遍历数组,拼接数组

NSString *absolutePath=[path stringByAppendingPathComponent:fileName];


第六步  计算文件大小


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


                          第三部分 缓存清理思路流程图


iOS缓存清理思路的实现_第1张图片




你可能感兴趣的:(iOS缓存清理思路的实现)