Memory Cache for IOS development (99)

Source: Internet
Author: User

This article will only introduce caching content into the memory, and the next article will introduce caching content on the iOS disk.

The purpose of using the cache is to allow the application to respond to user input more quickly and to run the program efficiently. Sometimes we need to cache the data obtained by the remote web server to reduce multiple requests to the same url.

We can use the NSURLCache class in the sdk for memory caching. NSURLRequest requires a cache parameter to describe how the requested url caches data. Let's take a look at its CachePolicy type.

1. NSURLRequestUseProtocolCachePolicy NSURLRequest default cache policy, which is defined using the Protocol.
2. NSURLRequestReloadIgnoringCacheData ignores the cache and downloads it directly from the original address.
3. NSURLRequestReturnCacheDataElseLoad can be downloaded from the original address only when no data exists in the cache.
4. NSURLRequestReturnCacheDataDontLoad only uses the cache data. If the cache does not exist, the request fails. It is used when no offline network connection mode is established;
5. NSURLRequestReloadIgnoringLocalAndRemoteCacheData: ignores local and remote cache data and downloads it directly from the original address, similar to NSURLRequestReloadIgnoringCacheData.
6 NSURLRequestReloadRevalidatingCacheData: verify whether the local data is the same as the remote data. If the local data is different, download the remote data. Otherwise, use the local data.

NSURLCache also provides many methods to facilitate the caching of applications. The following example shows how to reduce multiple requests to the same url. See the following code:

[Plain]
-(IBAction) buttonPress :( id) sender
 
{
 
NSString * paramURLAsString = @ "http://www.baidu.com /";
 
If ([paramURLAsString length] = 0 ){
 
NSLog (@ "Nil or empty URL is given ");
 
Return;
 
}
 
NSURLCache * urlCache = [NSURLCache sharedURLCache];
 
/* Set the cache size to 1 MB */
 
[UrlCache setMemoryCapacity: 1*1024*1024];
 
// Create an nsurl
 
NSURL * url = [NSURL URLWithString: paramURLAsString];
 
// Create a request
 
NSMutableURLRequest * request =
 
[NSMutableURLRequest
 
RequestWithURL: url
 
CachePolicy: NSURLRequestUseProtocolCachePolicy
 
TimeoutInterval: 60366f];
 
// Obtain the cache output from the request
 
NSCachedURLResponse * response =
 
[UrlCache cachedResponseForRequest: request];
 
// Determine whether a cache exists
 
If (response! = Nil ){
 
NSLog (@ "get data from cache if cache output exists ");
 
[Request setCachePolicy: NSURLRequestReturnCacheDataDontLoad];
 
}
 
Self. connection = nil;
 
/* Create NSURLConnection */
 
NSURLConnection * newConnection =
 
[[NSURLConnection alloc] initWithRequest: request
 
Delegate: self
 
StartImmediately: YES];
 
Self. connection = newConnection;
 
[NewConnection release];
 
}

In this example, the request url is www.baidu.com. If the url is cached, we can directly obtain data from the cache. Otherwise, we can retrieve data from www.baidu.com. We set the cache size to 1 MB.

Use the following code to print out the request process:

[Plain]
-(Void) connection :( NSURLConnection *) connection
 
DidReceiveResponse :( NSURLResponse *) response {
 
NSLog (@ "receive output ");
 
}
 
-(NSURLRequest *) connection :( NSURLConnection *) connection
 
WillSendRequest :( NSURLRequest *) request
 
RedirectResponse :( NSURLResponse *) redirectResponse {
 
NSLog (@ "request to be sent ");
 
Return (request );
 
}
 
-(Void) connection :( NSURLConnection *) connection
 
DidReceiveData :( NSData *) data {
 
NSLog (@ "Accept data ");
 
NSLog (@ "data length = % lu", (unsigned long) [data length]);
 
}
 
-(NSCachedURLResponse *) connection :( NSURLConnection *) connection
 
WillCacheResponse :( NSCachedURLResponse *) cachedResponse {
 
NSLog (@ "");
 
Return (cachedResponse );
 
}
 
-(Void) connectionDidFinishLoading :( NSURLConnection *) connection {
 
NSLog (@ "request completed ");
 
}
 
-(Void) connection :( NSURLConnection *) connection
 
DidFailWithError :( NSError *) error {
 
NSLog (@ "request failed ");
 
}

Result of the first button:


16:26:18. 959 CacheDataTest [2838: c07] request to be sent

16:26:19. 029 CacheDataTest [2838: c07] will receive the output

16:26:19. 029 CacheDataTest [2838: c07] accept data

16:26:19. 029 CacheDataTest [2838: c07] Data Length = 2896

16:26:19. 032 CacheDataTest [2838: c07] accept data

16:26:19. 032 CacheDataTest [2838: c07] Data Length = 4344

16:26:19. 033 CacheDataTest [2838: c07] accept data

16:26:19. 033 CacheDataTest [2838: c07] Data Length = 1448

16:26:19. 036 CacheDataTest [2838: c07] accept data

16:26:19. 036 CacheDataTest [2838: c07] Data Length = 1749

16:26:19. 037 CacheDataTest [2838: c07]

16:26:19. 037 CacheDataTest [2838: c07] ADDRESPONSE-adding to memory only: http://www.baidu.com/

16:26:19. 037 CacheDataTest [2838: c07] request completed

After reading the button on the page for the second time, the print result is as follows:


18:52:18. 894 Caching [3971: 207] The request will be sent soon


18:52:18. 895 Caching [3971: 207] will receive the output

18:52:18. 895 Caching [3971: 207] accept data

18:52:18. 896 Caching [3971: 207] Data Length = 7410

18:52:18. 896 Caching [3971: 207] request completed

We can see that there is no "outputs the cache" item. The requested data is the accumulation of the first request, that is, the second request is to obtain data from the memory.

 


 

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.