The basic _ios of IOS system cache development

Source: Internet
Author: User

I. Multiple requests for the same URL

Sometimes, the same URL is requested many times, the returned data may be the same, such as a picture on the server, no matter how many times the download, the returned data are the same.

The above situation will cause the following problems

(1) Waste of user traffic

(2) The program response speed is not fast enough

To solve the above problem, generally consider caching the data.


Second, the cache


To increase the response speed of your program, consider using caching (memory cache \ Hard disk caching)

The first time the data is requested, there is no data in the memory cache and no data in the hard disk cache.

The process of caching data

When the server returns data, the following steps are required

(1) Use of server data (e.g. parsing, display)

(2) caching the server's data to the hard disk (sandbox)

The caching scenario is that there is data in the memory cache and there is data in the hard disk cache.

The request for data is divided into two scenarios:

(1) If the program has not been closed, has been running

Then there is data in the memory cache, and there is data in the hard disk cache. If you request the data again at this time, you can use the data directly in the memory cache

(2) If the program is restarted

Then the memory cache has disappeared, no data, hard disk cache still exists, and data. If you request the data again at this time, you need to read the cached data in memory.

Tip: After reading data from the hard disk cache, there is data in the memory cache



Third, the implementation of the cache

1. Description:

Because get requests are generally used to query data, POST requests typically send a large amount of data to the server (more variable)

As a result, only the GET request is cached, not the POST request.

In iOS, you can use the Nsurlcache class to cache data

Prior to IOS 5: Only memory cache is supported. Starting with iOS 5: both memory cache and hard disk caching are supported



2.NSURLCache

The cache technology in iOS uses the Nsurlcache class.

Caching principle: A nsurlrequest corresponds to a nscachedurlresponse

Caching technology: Saves the cached data to the database.



Common usage of 3.NSURLCache

(1) Obtain the global cache object (no need to manually create) Nsurlcache *cache = [Nsurlcache Sharedurlcache];

(2) Set the maximum capacity of the memory cache (in bytes, the default is 512KB)-(void) Setmemorycapacity: (Nsuinteger) memorycapacity;

(3) Set the maximum capacity of the hard disk cache (in bytes, the default is 10M)-(void) Setdiskcapacity: (Nsuinteger) diskcapacity;

(4) Location of the hard disk cache: Sandbox/library/caches

(5) Obtaining a cache of a request-(Nscachedurlresponse *) Cachedresponseforrequest: (nsurlrequest *) request;

(6) Clears a request's cache-(void) Removecachedresponseforrequest: (nsurlrequest *) request;

(7) Clear all Cache-(void) removeallcachedresponses;



4. Cache GET Request

It's very simple to cache a GET request for data caching

Copy Code code as follows:

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

Setting caching policies

Request.cachepolicy = Nsurlrequestreturncachedataelseload;

The system automatically uses Nsurlcache for data caching whenever a caching policy is set up



5.iOS provides 7 caching strategies for Nsurlrequest: (In fact, only 4 of them are available)
Copy Code code as follows:

Nsurlrequestuseprotocolcachepolicy//Default Caching policy (depending on protocol)

Nsurlrequestreloadignoringlocalcachedata//Ignore cache, re-request

Nsurlrequestreloadignoringlocalandremotecachedata//Not implemented

Nsurlrequestreloadignoringcachedata = nsurlrequestreloadignoringlocalcachedata//Ignore cache, re-request

Cache is nsurlrequestreturncachedataelseload//with cache, and is requested again without caching

nsurlrequestreturncachedatadontload//cache with cache, no cache, no request, as a request error processing (for offline mode)

Nsurlrequestreloadrevalidatingcachedata//Not implemented



6. Considerations for Caching

The caching settings need to be considered for specific circumstances, if a URL's return data is requested:

(1) Frequently updated: Cannot use the cache! such as stocks, lottery data

(2) Immutable: decisively with the cache

(3) Occasional update: You can change the cache policy periodically or clear the cache

Tip: If you use a lot of caching, it will accumulate, and it is recommended that you periodically clear the cache

Four, local cache development related
In order to save traffic, but also for a better user experience, at present, many applications are using the local caching mechanism, which netease news caching is the most outstanding function. My own application also wanted to be part of the local caching function, so I looked up the relevant data from the Internet and found that there were two approaches in general. One is to write their own cache processing, one is the use of asihttprequest in the Asidownloadcache.

Method One: Generally save the first data returned by the server in the sandbox. This allows data to be read locally when the phone is disconnected from the network.
1. The code to save to the sandbox:

Copy Code code as follows:

+ (void) Savecache: (int) type andid: (int) _id andstring: (NSString *) str;
{
Nsuserdefaults * setting = [Nsuserdefaults standarduserdefaults];
NSString * key = [NSString stringwithformat:@ "detail-%d-%d", type, _id];
[Setting Setobject:str Forkey:key];
[Setting synchronize];
}


2. Read the code for the local sandbox

Before reading, the local is first judged by type and ID

Copy Code code as follows:

+ (NSString *) GetCache: (int) type andid: (int) _id
{
Nsuserdefaults * settings = [Nsuserdefaults standarduserdefaults];
NSString *key = [NSString stringwithformat:@ "detail-%d-%d", type, _id];

NSString *value = [Settings Objectforkey:key];
return value;
}


If there's data in the sandbox,

Copy Code code as follows:

NSString *value = [Tool getcache:5 andid:self. Qiutime];
if (value) {
Nsdictionary *backdict = [value jsonvalue];
if ([Backdict objectforkey:@ "items"]) {
Nsarray *array=[nsarray arraywitharray:[backdict objectforkey:@ "items"]];
For (nsdictionary *qiushi in array) {
Qiushi *qs=[[[qiushi Alloc]initwithdictionary:qiushi] autorelease];
[Self.list Addobject:qs];
}
}
[Self.tableview Reloaddata];

}

[Self.tableview tableviewdidfinishedloadingwithmessage:@ "data is all loaded ..."];
Self.tableView.reachedTheEnd = YES;


Method Two: Implement local caching using ASIHTTPRequest and Asidownloadcache

1, set the global cache
Add a global variable to the AppDelegate.h
Copy Code code as follows:

@interface Appdelegate:uiresponder
{
Asidownloadcache *mycache;
}
@property (Strong, nonatomic) UIWindow *window;
@property (Nonatomic,retain) Asidownloadcache *mycache;


In APPDELEGATE.M-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (NSDictionary *) Add the following code to the Launchoptions method

Copy Code code as follows:

Custom Caching
Asidownloadcache *cache = [[Asidownloadcache alloc] init];
Self.mycache = cache;
[Cache release];

Set Cache path
Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *documentdirectory = [Paths objectatindex:0];
[Self.mycache setstoragepath:[documentdirectory stringbyappendingpathcomponent:@ "resource"]];
[Self.mycache Setdefaultcachepolicy:asionlyloadifnotcachedcachepolicy];


Add the following statement to the Dealloc method in APPDELEGATE.M
Copy Code code as follows:

[Mycache release];

So far, the declaration of global variables has been completed.

2. Set Caching policy
Set the way the request is stored where the ASIHTTPRequest request is implemented, with the following code

Copy Code code as follows:

NSString *str = @ "http://....../getPictureNews.aspx";
Nsurl *url = [Nsurl urlwithstring:str];
ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url];
Get Global variables
Appdelegate *appdelegate = [[UIApplication sharedapplication] delegate];
Set caching mode
[Request SetDownloadCache:appDelegate.myCache];
Set the caching data Storage policy, where you can read cached data without updating or networking
[Request Setcachestoragepolicy:asicachepermanentlycachestoragepolicy];
Request.delegate = self;
[Request startasynchronous];

3. Clean up cached data

I'm here to manually clean up the data, add the following code where appropriate, and I'll put the cleanup cache in the application's Setup module:

Copy Code code as follows:

Appdelegate *appdelegate = [[UIApplication sharedapplication] delegate];
[Appdelegate.mycache Clearcachedresponsesforstoragepolicy:asicachepermanentlycachestoragepolicy];

This is asicachepermanentlycachestoragepolicy the cached data for this storage policy, and if other parameters are replaced, the cached data for the corresponding storage policy can be cleaned up.

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.