To save traffic and improve user experience, many applications currently use the local cache mechanism. Among them, Netease news provides the best caching function. My own applications also want to add the local cache function, so I checked the relevant information on the Internet and found that there are two methods in general. One is self-writing cache processing, and the other is using ASIDownloadCache in ASIHTTPRequest. Based on my current technical skills and time spent, I decided to select the latter, and it turns out that the effect is quite good. The implementation method is as follows:
1. Set global Cache
Add a global variable to AppDelegate. h.
[Plain]
@ Interface AppDelegate: UIResponder <UIApplicationDelegate>
{
ASIDownloadCache * myCache;
}
@ Property (strong, nonatomic) UIWindow * window;
@ Property (nonatomic, retain) ASIDownloadCache * myCache;
Add the following code to the-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions method in AppDelegate. m:
[Plain]
// Custom Cache
ASIDownloadCache * cache = [[ASIDownloadCache alloc] init];
Self. myCache = cache;
[Cache release];
// Set the 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:
[Plain]
[MyCache release];
So far, the global variable declaration has been completed.
2. Set cache policies
Set the storage method of the request where the ASIHTTPRequest request is implemented. The Code is as follows:
[Plain]
NSString * str = @ "http: // ....../getPictureNews. aspx ";
NSURL * url = [NSURL URLWithString: str];
ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url];
// Obtain global variables
AppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
// Set the cache Mode
[Request setDownloadCache: appDelegate. myCache];
// Set the cache data storage policy. Here, the cache data is read if there is no update or cannot be connected to the Internet.
[Request setCacheStoragePolicy: ASICachePermanentlyCacheStoragePolicy];
Request. delegate = self;
[Request startAsynchronous];
3. Clear cache data
Here I am using the manual data cleanup method. Add the following code in the appropriate place. I put the cleanup cache in the application setting module:
[Plain]
AppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
[AppDelegate. myCache implements achedresponsesforstoragepolicy: ASICachePermanentlyCacheStoragePolicy];
Here, the cache data of the storage policy ASICachePermanentlyCacheStoragePolicy is cleared. If other parameters are replaced, the cache data of the corresponding storage policy can be cleared.