Memory Cache Mechanism for iOS development

Source: Internet
Author: User

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:

 
 
  1. -(IBAction) buttonPress :( id) sender
  2. {
  3. NSString * paramURLAsString = @ "http://www.baidu.com /";
  4. If ([paramURLAsString length] = 0 ){
  5. NSLog (@ "Nil or empty URL is given ");
  6. Return;
  7. }
  8. NSURLCache * urlCache = [NSURLCache sharedURLCache];
  9. /* Set the cache size to 1 MB */
  10. [UrlCache setMemoryCapacity: 1*1024*1024];
  11. // Create an nsurl
  12. NSURL * url = [NSURL URLWithString: paramURLAsString];
  13. // Create a request
  14. NSMutableURLRequest * request =
  15. [NSMutableURLRequest
  16. RequestWithURL: url
  17. CachePolicy: NSURLRequestUseProtocolCachePolicy
  18. TimeoutInterval: 60366f];
  19. // Obtain the cache output from the request
  20. NSCachedURLResponse * response =
  21. [UrlCache cachedResponseForRequest: request];
  22. // Determine whether a cache exists
  23. If (response! = Nil ){
  24. NSLog (@ "get data from cache if cache output exists ");
  25. [Request setCachePolicy: NSURLRequestReturnCacheDataDontLoad];
  26. }
  27. Self. connection = nil;
  28. /* Create NSURLConnection */
  29. NSURLConnection * newConnection =
  30. [[NSURLConnection alloc] initWithRequest: request
  31. Delegate: self
  32. StartImmediately: YES];
  33. Self. connection = newConnection;
  34. [NewConnection release];
  35. }

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:

 
 
  1. -(Void) connection :( NSURLConnection *) connection
  2. DidReceiveResponse :( NSURLResponse *) response {
  3. NSLog (@ "receive output ");
  4. }
  5. -(NSURLRequest *) connection :( NSURLConnection *) connection
  6. WillSendRequest :( NSURLRequest *) request
  7. RedirectResponse :( NSURLResponse *) redirectResponse {
  8. NSLog (@ "request to be sent ");
  9. Return (request );
  10. }
  11. -(Void) connection :( NSURLConnection *) connection
  12. DidReceiveData :( NSData *) data {
  13. NSLog (@ "Accept data ");
  14. NSLog (@ "data length = % lu", (unsigned long) [data length]);
  15. }
  16. -(NSCachedURLResponse *) connection :( NSURLConnection *) connection
  17. WillCacheResponse :( NSCachedURLResponse *) cachedResponse {
  18. NSLog (@ "");
  19. Return (cachedResponse );
  20. }
  21. -(Void) connectionDidFinishLoading :( NSURLConnection *) connection {
  22. NSLog (@ "request completed ");
  23. }
  24. -(Void) connection :( NSURLConnection *) connection
  25. DidFailWithError :( NSError *) error {
  26. NSLog (@ "request failed ");
  27. }

When we click the button on the interface for the first time, the output is as follows:

 
 
  1. 18:50:24. 910 Caching [3971: 207] The request will be sent soon
  2. 18:50:28. 557 Caching [3971: 207] will receive the output
  3. 18:50:31. 677 Caching [3971: 207] accept data
  4. 18:50:31. 681 Caching [3971: 207] Data Length = 4414
  5. 18:50:31. 682 Caching [3971: 207] accept data
  6. 18:50:31. 682 Caching [3971: 207] Data Length = 2996
  7. 18:50:38. 107 Caching [3971: 207]
  8. 18:50:38. 109 Caching [3971: 207] request completed

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

 
 
  1. 18:52:18. 894 Caching [3971: 207] The request will be sent soon
  2. 18:52:18. 895 Caching [3971: 207] will receive the output
  3. 18:52:18. 895 Caching [3971: 207] accept data
  4. 18:52:18. 896 Caching [3971: 207] Data Length = 7410
  5. 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.

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.