ios-Cache Processing

Source: Internet
Author: User

1. What needs to be cached?      frequently changing data does not need to be cached, unchanging data needs to be cached       images and microblogging interface Weibo data, etc., will not change, need to cache       2. What controls or frameworks are in the project default help us do some cache processing?      Wkwebview system did a cache, sdwebimage 3. We came to the sandbox path sdwebimage cache directory, found inside the image name is very special, how to deal with the?      First, we know that if there is a file with the same name, then the file will be overwritten by the previous overwrite       In order to prevent being overwritten, the file is generally encrypted and processed  4. Why encrypt?    encryption is to handle the cache file to get different file name, prevent being overwritten  5. How to encrypt?       Generally there are two ways to encrypt cached files      1. Get the file binary data, first base64 encryption, and then encrypt the resulting text file MD5 encryption   The resulting hash value as the name of the file      2. MD5 encrypt the URL directly, the hash value as the file name (Sdwebimage is this way)      6. If two different URLs point to the same image, use the first method above to encrypt The resulting hash value is the same as     what to do?      This time we can add salt to the text file (date, URL, random number as salt) before MD5 encryption, so the resulting hash value will be different.      7. How to get the cache size (size)?      If you do not cache processing, then we can see sdwebimage how to do cache processing       ENTER SDImageCache.h See how the framework is handled, we find a lot of ways to handle caching      -(void) Storeimage: (UIImage *) image forkey: (NSString *)key;     -(void) cleardisk;       Clean up disk cache      -(void) cleandisk;       Cleanup of expired disk caches      -(Nsuinteger) getsize;       Get cached dimensions       Other methods you can go to the head file yourself to see, learn (there is a text top translation Sdwebimage can help us learn)       We can get the buffer size according to the framework method, imitate a own method  8. How to imitate?      jump in-(Nsuinteger) GetSize; method, how to implement the analysis method and then imitate      //Get the total size of the disk cache file
-(Nsuinteger) getsize {__block Nsuinteger size = 0; Synchronous + Serial Queue: Executing code in block in the current thread
Dispatch_sync (Self.ioqueue, ^{
Get all sub-paths below the Diskcachepath path
Nsdirectoryenumerator *fileenumerator = [_filemanager EnumeratorAtPath:self.diskCachePath];
Traverse to get the size of all sub-paths corresponding files and accumulate to calculate the total size of all files
For (NSString *filename in FileEnumerator) {
Full path of the stitching file
NSString *filepath = [Self.diskcachepath stringbyappendingpathcomponent:filename];
Gets the dictionary of properties for the specified file
Nsdictionary *attrs = [[Nsfilemanager Defaultmanager] Attributesofitematpath:filepath Error:nil];
Accumulate file size call FileSize to get file size = = attrs["Nsfileszie"]
Size + = [Attrs fileSize];
}
});
return size;} 9. After the analysis we summarize the steps to get the cache size 9.1 Create a File Manager Object 9.2 Get the path under a path for all files 9.3 traverse all files 9.4 stitching the full path of the file 9.5 get file attributes 9.6 put each The size (size) of the file adds up to the size of the cache. We just need to change the path to get the size of the specified folder (size)//get Sdwebimage Cache Size
-(void) getsize
{
Get folder path
NSString *cachepath = Xmgcachepath;
NSString *defaultpath = [Xmgcachepath stringbyappendingpathcomponent:@ "Default"];
Nsinteger totalsize = 0;
1. Get the File Manager object
Nsfilemanager *mgr = [Nsfilemanager Defaultmanager];

2. Get all Files (delivery folder path)
Path: Folder path
Subpathsatpath: Gets all sub-paths in a folder, including multi-level paths
Nsarray *subpaths = [Mgr Subpathsatpath:defaultpath];
3. Traverse All Files
For (NSString *subpath in subpaths) {
4. Stitching the full file name
NSString *filepath = [DefaultPath Stringbyappendingpathcomponent:subpath];

Determine if the file is hidden
if ([Subpath hasprefix:@]. DS "]) continue;

Whether it is a folder
BOOL isdirectory;
Determine if the file exists and whether it is a folder
[Mgr Fileexistsatpath:filepath isdirectory:&isdirectory];
if (isdirectory) continue;

5.attributesOfItemAtPath: Pass in file full path, can get file attribute
Nsdictionary *attr = [Mgr Attributesofitematpath:filepath error:nil];
6. Add the file size
        totalsize + = [attr filesize];   } }     10.return  break  continue   differences      return: Jump directly out of the current method      break: Jump directly out of the current loop      continue: Jump out of this loop and go to the next round of  11. How to display the cache size to the interface?      11.1 First we understand the file size of the unit conversion           on the computer: 1M = 1024KB  1kb = 1024b        &NBSP ; On the phone: 1M = 1000KB  1kb = 1000b     11.2 We can first define a string to stitch the cache size           The cache size returned by the system In B           We need to show the final format:   clear cache (XXX B)   or   clear cache (xx.x KB)   or   purge slow Save (xx.x M)           1. Get Cache size           2. To determine if it is greater than/+ +   greater than Otalsize (cache size)/($ * +)   Keep one decimal place               /  Get results   mosaic Clear Cache (xx.x M)           3. Determine if it is greater than 1000  If it is greater then use TotalSize (cache size)/  Reserve a decimal place                  get the knot Fruit   stitching into clear cache (xx.x KB)           4. Both do not meet the above conditions   directly take totalsize stitching into   clear cache (xx.x KB)   &N Bsp       5. Then replace. 0 with null      -(NSString *) cachestr
{
Calculate Cache buffer Size
Nsinteger cacheSize = [self getsizeofdirectorypath:xmgcachepath]; CGFloat Cachesizef;
NSString *sizestr = @ "Clear cache";
if (cacheSize > * +) {//MB
Cachesizef = cacheSize/(1000.0 * 1000.0);
SIZESTR = [NSString stringwithformat:@ "%@ (%.1FMB)", Sizestr,cachesizef];
} else if (CacheSize > +) {//KB
Cachesizef = cachesize/1000.0;
SIZESTR = [NSString stringwithformat:@ "%@ (%.1FKB)", Sizestr,cachesizef];
} else if (CacheSize > 0) {//B
SIZESTR = [NSString stringwithformat:@ "%@ (%LDB)", sizestr,cachesize]; Replace. 0 with empty sizestr = [Sizestr stringbyreplacingoccurrencesofstring:@ ". 0" withstring:@ ""];
return SIZESTR;}     12. How do I clear the cache? To see how sdwebimage clears the cache, we can summarize the steps to clear the cache 1. Create a File Manager 2. Delete the folder under the specified path 3. Create an empty folder Note: After we clear the cache, we must refresh the table in order to let the displayed cache data update in real time// Clicking on the cell will call
-(void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) Indexpath
{
Empty cache
Nsfilemanager *mgr = [Nsfilemanager Defaultmanager];
1. Delete the cache folder
[Mgr Removeitematpath:xmgcachepath Error:nil];
2. Create a new cache folder
[Mgr Createdirectoryatpath:xmgcachepath withintermediatedirectories:yes attributes:nil Error:nil];     Refresh table Global Refresh [Self.tableview reloaddata];}     Local Refresh (animation refresh) (delete the specified line and refresh) Nsarray *indexpaths = @[[nsindexpath indexpathforrow:0 insection:0]];     Insert the specified line and refresh [Self.tableview insertrowsatindexpaths:indexpaths withrowanimation:uitableviewrowanimationtop]; Nsarray *indexpaths = @[
[Nsindexpath indexpathforrow:0 insection:0],
[Nsindexpath indexpathforrow:1 insection:0];    Delete the specified line and refresh [Self.tableview deleterowsatindexpaths:indexpaths withrowanimation:uitableviewrowanimationmiddle]; Refreshes the specified line Self.tableview reloadrowsatindexpaths:<# (nonnull nsarray<nsindexpath *> *) #> withRowAnimation:& lt;# (uitableviewrowanimation) #>

ios-Cache Processing

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.