iOS清除所有缓存的实例代码
本文介绍了iOS清除所有缓存的实例代码,分享给大家,具体如下:
计算缓存
NSString*libPath=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES)[0]; CGFloatfileSize=[selffolderSizeAtPath:libPath]; -(float)folderSizeAtPath:(NSString*)folderPath{ NSFileManager*manager=[NSFileManagerdefaultManager]; if(![managerfileExistsAtPath:folderPath])return0; NSEnumerator*childFilesEnumerator=[[managersubpathsAtPath:folderPath]objectEnumerator]; NSString*fileName; longlongfolderSize=0; while((fileName=[childFilesEnumeratornextObject])!=nil){ NSString*fileAbsolutePath=[folderPathstringByAppendingPathComponent:fileName]; folderSize+=[selffileSizeAtPath:fileAbsolutePath]; } returnfolderSize/(1024.0*1024.0); } -(longlong)fileSizeAtPath:(NSString*)filePath{ NSFileManager*manager=[NSFileManagerdefaultManager]; if([managerfileExistsAtPath:filePath]){ return[[managerattributesOfItemAtPath:filePatherror:nil]fileSize]; } return0; }
清除缓存
-(void)action:(id)sender { NSArray*paths=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES); NSString*path=[pathslastObject]; NSArray*files=[[NSFileManagerdefaultManager]subpathsAtPath:path]; for(NSString*pinfiles){ NSError*error; NSString*Path=[pathstringByAppendingPathComponent:p]; if([[NSFileManagerdefaultManager]fileExistsAtPath:Path]){ //清理缓存,保留Preference,里面含有NSUserDefaults保存的信息 if(![PathcontainsString:@"Preferences"]){ [[NSFileManagerdefaultManager]removeItemAtPath:Patherror:&error]; } }else{ } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。