Calculate the size of the disk cache folder in iOS

Source: Internet
Author: User

Sdwebimage framework in the process of automatic disk caching, the underlying implementation of the cache size, the framework of the method name is GetSize, but the method is not easy to understand, I wrote a new, annotated

Basic idea: 1. Remove the cache first to get the path to the file

2. Using Nsfilemanager, remove all sub-paths under the file to return an array

3. Iterate through the array, take advantage of the file's FileSize property, and add the file out of each sub-path, that is, the size of the folder

Note: Note that hidden files in the folder will cause the resulting file size to deviate

The resulting size is B, if you want to convert m in an Apple phone (need to remove (1000.0 * 1000.0))

Get the Cache folder path

NSString *cachepath = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) firstObject];

Create a File Manager single grain (to manage files, you must use Nsfilemanager)

Nsfilemanager *mgr = [Nsfilemanager Defaultmanager];

Get the folder all sub-path array: Get the file path in the multilevel directory

Nsarray *subpaths = [Mgr Subpathsatpath:cachepath];

Traverse

int totalsize = 0;

For (NSString *subpath in subpaths) {

Stitching each Sliver path

NSString *filepath = [CachePath Stringbyappendingpathcomponent:subpath];

Determines whether a hidden file (. DS is a hidden file in Apple), if you hide the file, skip that execution and go to the next execution

if ([FilePath containsstring:@]. DS "]) continue;

Determine if it is a folder

BOOL isdirectory = NO;

If the file does not exist or is a folder, skip

BOOL isexists = [Mgr Fileexistsatpath:filepath isdirectory:&isdirectory];

if (!isexists | | isdirectory) continue;

Get file attributes (take advantage of the file's FileSize property)

Nsdictionary *attr = [Mgr Attributesofitematpath:filepath error:nil];

TotalSize + = [attr fileSize];

Calculate the size of the disk cache folder in iOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.