iOS development local cache (data offline cache, read, release)

Source: Internet
Author: User

In order to save traffic, but also for a better user experience, many applications now use a local caching mechanism, in which NetEase news cache function is the most outstanding. My own application also wanted to join the local cache function, so I looked up the relevant information on the Internet and found that there are two methods in general. One is the processing of their own write cache, one is the use of asihttprequest in the Asidownloadcache.

Method One: The data returned by the server is generally stored in the sandbox. This allows the data to be read locally when the phone is disconnected from the network.

1. Save the code to the sandbox:

[Plain]View Plaincopy
    1. + (void) Savecache: (int) type andid: (int) _id andstring: (NSString *) str;
    2. {
    3. Nsuserdefaults * setting = [Nsuserdefaults standarduserdefaults];
    4. NSString * key = [NSString stringwithformat:@ "detail-%d-%d", type, _id];
    5. [Setting Setobject:str Forkey:key];
    6. [Setting synchronize];
    7. }

2. Read the local sandbox code

Before reading, first determine if there is a local based on the type and ID

[Plain]View Plaincopy
    1. + (NSString *) GetCache: (int) type andid: (int) _id
    2. {
    3. Nsuserdefaults * settings = [Nsuserdefaults standarduserdefaults];
    4. NSString *key = [NSString stringwithformat:@ "detail-%d-%d", type, _id];
    5. NSString *value = [Settings Objectforkey:key];
    6. return value;
    7. }

If there's data in the sandbox,

[Plain]View Plaincopy
  1. NSString *value = [Tool getcache:5 andid:self. Qiutime];
  2. if (value) {
  3. Nsdictionary *backdict = [value jsonvalue];
  4. if ([Backdict objectforkey:@ "items"]) {
  5. Nsarray *array=[nsarray arraywitharray:[backdict objectforkey:@ "items"];
  6. For (nsdictionary *qiushi in array) {
  7. Qiushi *qs=[[[qiushi Alloc]initwithdictionary:qiushi] autorelease];
  8. [Self.list Addobject:qs];
  9. }
  10. }
  11. [Self.tableview Reloaddata];
  12. }
  13. [Self.tableview tableviewdidfinishedloadingwithmessage:@ "Data all Loaded up ..."];
  14. Self.tableView.reachedTheEnd = YES;

Method Two: Implement local cache using ASIHTTPRequest and Asidownloadcache

1, set the global cache
Add a global variable in AppDelegate.h

[Plain]View Plaincopy
    1. @interface Appdelegate:uiresponder
    2. {
    3. Asidownloadcache *mycache;
    4. }
    5. @property (Strong, nonatomic) UIWindow *window;
    6. @property (Nonatomic,retain) Asidownloadcache *mycache;

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

[Plain]View Plaincopy
    1. Custom Cache
    2. Asidownloadcache *cache = [[Asidownloadcache alloc] init];
    3. Self.mycache = cache;
    4. [Cache release];
    5. Set the cache path
    6. Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
    7. NSString *documentdirectory = [Paths objectatindex:0];
    8. [Self.mycache setstoragepath:[documentdirectory stringbyappendingpathcomponent:@ "resource"];
    9. [Self.mycache Setdefaultcachepolicy:asionlyloadifnotcachedcachepolicy];
    

Add the following statement to the Dealloc method in APPDELEGATE.M

[Plain]View Plaincopy
    1. [Mycache release];

The declaration of the global variable has been completed so far.

2. Set the cache policy

Set the request storage location where the ASIHTTPRequest requests are implemented, as shown in the code below

[Plain]View Plaincopy
    1. NSString *str = @ "http://....../getPictureNews.aspx";
    2. Nsurl *url = [Nsurl urlwithstring:str];
    3. ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url];
    4. Get Global variables
    5. Appdelegate *appdelegate = [[UIApplication sharedapplication] delegate];
    6. Set Cache mode
    7. [Request SetDownloadCache:appDelegate.myCache];
    8. Set the cache data Storage policy, where the cached data is read if it is not updated or is not networked
    9. [Request Setcachestoragepolicy:asicachepermanentlycachestoragepolicy];
    10. Request.delegate = self;
    11. [Request startasynchronous];

3. Clean up cached data

What I'm using here is to manually clean up the data, add the following code where appropriate, and I'll clean up the cache in the app's setup module:

[Plain]View Plaincopy
    1. Appdelegate *appdelegate = [[UIApplication sharedapplication] delegate];
    2. [Appdelegate.mycache Clearcachedresponsesforstoragepolicy:asicachepermanentlycachestoragepolicy];

This is the asicachepermanentlycachestoragepolicy cache of this storage policy, and if you replace other parameters, you can clean up the cached data for the corresponding storage policy. (Reference: http://zycto.blog.163.com/blog/static/17152400201110221340738/)

iOS development local cache (data offline cache, read, release)

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.