Three ways IOS handles caching

Source: Internet
Author: User

Caching processing is a pretty headache, and you need to synthesize different strategies as needed. In general, there are several situations:

1.URL caching, such as post browsing for social apps, is a URL cache in Viewdidappear:. In simple terms, the Nsurlcache class is used, first in the APPDELEGATE.M.

-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions method to create a Nsurlcache single example:

Set the memory cache size
Nsurlcache *urlcache = [[Nsurlcache alloc] initwithmemorycapacity:4 * 1024x768 * 1024x768 diskcapacity:10 * 1024x768 * 1024x768 diskpath:n IL];
[Nsurlcache Setsharedurlcache:urlcache];
Then the viewcontroller.m inside the implementation method:

Network Cache Response Method

-(Ibaction) Senderbutton: (ID) Sender {//Weather API Interfacensstring* Path =@"http://www.weather.com.cn/data/sk/101110101.html"; [Self Getbyurl:path andcallback:^(IDobj) {NSString*str =[[NSString alloc]initwithdata:obj encoding:nsutf8stringencoding]; NSLog (@"=========================================================\n"); NSLog (@"Post Cache test:%@", str); NSLog (@"=========================================================\n"); }];

}

Memory caching method for network requests

-(void) Getbyurl: (NSString *) path Andcallback: (CallBack) callback{nsstring* Pathstr =[path stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; Nsurl*url =[Nsurl Urlwithstring:pathstr]; Nsmutableurlrequest*request =[Nsmutableurlrequest Requestwithurl:url];    [Request Setcachepolicy:nsurlrequestreloadrevalidatingcachedata]; Nscachedurlresponse* Response =[[Nsurlcache Sharedurlcache] cachedresponseforrequest:request]; //determine if there is a cache    if(Response! =Nil) {NSLog (@"have cache");    [Request Setcachepolicy:nsurlrequestreturncachedatadontload]; }Else{NSLog (@"No Cache"); }        //Create Nsurlconnectionnsdata* data =[nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil];    callback (data); }

2. File cache, such as user information and other basic unchanged information stored in the local sandbox

User information cache file saved in sandbox

-(Ibaction) Usercache: (UIButton *) Sender {    = [self savefiletodocuments:@]/http www.weather.com.cn/data/sk/101020100.html"];}
//save file to sandbox-(NSString *) savefiletodocuments: (NSString *) url{NSString*resultfilepath =@""; NSString*destfilepath = [[Nshomedirectory () stringByAppendingPathComponent:@"Documents"] Stringbyappendingpathcomponent:url];//add URL, combine cost to file pathNSString *destfolderpath =[Destfilepath stringbydeletinglastpathcomponent]; //determines whether the path folder exists or does not exist to create        if(![[Nsfilemanager Defaultmanager] Fileexistsatpath:destfolderpath]) {NSLog (@"folder does not exist, new folder"); [[Nsfilemanager Defaultmanager] createdirectoryatpath:destfolderpath withintermediatedirectories:yes attributes:        Nil Error:nil]; }                //determine if the file has been downloaded        if([[[Nsfilemanager Defaultmanager] Fileexistsatpath:destfilepath]) {NSLog (@"file is downloaded \ n"); Resultfilepath=Destfilepath; } Else{NSLog (@"no cache, request data \ n"); NSData*userinfodata =[NSData Datawithcontentsofurl:[nsurl Urlwithstring:url]; if([Userinfodata writetofile:destfilepath Atomically:yes]) {Resultfilepath=Destfilepath; }} NSData*userinfodata=[[Nsfilemanager Defaultmanager] contentsatpath:resultfilepath]; NSString* str =[[NSString Alloc]initwithdata:userinfodata encoding:nsutf8stringencoding]; NSLog (@"=========================================================\n"); NSLog (@"user:%@", str); NSLog (@"=========================================================\n"); returnResultfilepath;}

3. Picture cache is the most important, the cost of traffic also accounted for memory, so we recommend the use of third-party sdwebimage

The simplest is to use this method:

[Self.imageview sd_setimagewithurl:url completed:^ (UIImage *image, Nserror *error, Sdimagecachetype cacheType, NSURL *ImageURL) {        if(cachetype==Sdimagecachetypenone) {NSLog (@"no cache, download from network"); }Else if(cachetype==Sdimagecachetypedisk) {NSLog (@"have cache, read from disk"); }Else{NSLog (@"have cache, read from memory"); }    }];

To know the internal mechanism of this method, see here.

Want to download this demo.

Reprint please specify the source!

Three ways IOS handles caching

Related Article

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.