How to customize encrypted cache and Cache principles in iOS (Section 1: Analysis of Cache principles)

Source: Internet
Author: User

How to customize encrypted cache and Cache principles in iOS (Section 1: Analysis of Cache principles)

Recently, a friend asked me how to implement an image caching function on my own. To tell the truth, I have not studied how to cache images in projects? And what if you need a more confidential cache? I have done a good caching function in the project, so I will introduce it to you. Please forgive me. My vision is limited.

First of all, we understand that there is a cache class for OC, and the key is how to use it.

@ Interface NSCache: NSObject {
-(Id) objectForKey :( id) key;
-(Void) setObject :( id) obj forKey :( id) key; // 0 cost
 

The above two red Methods tell us that the method used is to save data by setting dictionary key-value pairs. Therefore, the cache class is a custom dictionary. To Cache data, you only need to make the dictionary unique on all pages of the app. Therefore, you need to set it as a singleton class, for more information about the singleton type, see.

Another point you may not consider is that there is also a folder named cache in our sandbox. This is the folder for storing cached data, so we need to use it together.

How can we work together?

The general idea is to save the class to the cache singleton and save it in the sandbox cache (save it to the sandbox cache and remember to execute it in the main thread, when obtaining the data, first obtain the cached data in the cache class. If the data does not exist in the cache folder of the sandbox, the obtained data will not exist until it is found.

Let's take a look at how the AFNetworking source code caches images.

 

// UIImageView+AFNetworking.m//// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com)//// Permission is hereby granted, free of charge, to any person obtaining a copy// of this software and associated documentation files (the "Software"), to deal// in the Software without restriction, including without limitation the rights// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell// copies of the Software, and to permit persons to whom the Software is// furnished to do so, subject to the following conditions://// The above copyright notice and this permission notice shall be included in// all copies or substantial portions of the Software.//// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.#import "UIImageView+AFNetworking.h"#import 
 
  #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)#import "AFHTTPRequestOperation.h"
 
// Cache class @ interface AFImageCache: NSCache @ end# Pragma mark-
// UIImageview category @ interface UIImageView (_ AFNetworking) @ property (readwrite, nonatomic, strong, setter = delimiter :) AFHTTPRequestOperation * af_imageRequestOperation; @ end @ implementation UIImageView (_ AFNetworking) + (NSOperationQueue *) initialize {static NSOperationQueue * _ queue = nil; static extends onceToken; dispatch_once (& onceToken, ^ {_ queue = [[NSOperationQueue alloc] init]; _ operator = Operator;}); return _ operator;}-(AFHTTPRequestOperation *) af_imageRequestOperation {return (AFHTTPRequestOperation *) operator (self, @ selector (af_imageRequestOperation ));} -(void) af_setImageRequestOperation :( AFHTTPRequestOperation *) imageRequestOperation {operator (self, @ selector (af_imageRequestOperation), imageRequestOperation, operator);} @ end # pragma mark-
// Image category @ implementation UIImageView (AFNetworking) @ dynamic Layout; + (id) specify dimagecache {static AFImageCache * _ latency = nil; static receivoncepredicate; dispatch_once (& oncePredicate, ^ {_ af_defaultImageCache = [[AFImageCache alloc] init]; [nsicationicationcenter defacenter center] addObserverForName: jsonobject: nil queue: [NSOperationQueue mainQueue] usingBlock: ^ (NSNotification * _ unused notification) {[_ af_defaultImageCache removeAllObjects] ;}] ;}); # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wgnu" returnObjc_getAssociatedObject (self, @ selector (nvidimagecache ))? : _ Af_defaultImageCache;
// Note that if we have a custom cache, We will directly return the custom cache. If not, we will return the AFImageCache inside the system, once manually set, we will return the custom
// Some students may think that this was the one we set at the beginning, and the next visit will not be gone. Note that this objc_getAssociatedObject is similar to that once userdefault is set, it will always exist unless it is cleared.
# Pragma clang diagnostic pop} + (void) setincludimagecache :( id) imageCache {objc_setAssociatedObject (self, @ selector (includimagecache), imageCache, identifier);}-(id) imageResponseSerializer {static id _ percent = nil; static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ percent = [AFImageResponseSerializer seriali Zer] ;}); # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wgnu" return objc_getAssociatedObject (self, @ selector (imageResponseSerializer ))? : _ Serialize; # pragma clang diagnostic pop}-(void) setImageResponseSerializer :( id) serializer {aggregate (self, @ selector (imageResponseSerializer), serializer, listener );} # pragma mark-// external interface for our use-(Void) setImageWithURL :( NSURL *) url {[self setImageWithURL: url placeholderImage: nil];}
 
Cept
// The first step of internal implementation is to add an accept attribute (specifying the type of image that can be submitted through file upload)-(void) setImageWithURL :( NSURL *) url placeholderImage :( UIImage *) placeholderImage {NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; [request addValue: @ "image/*" Accept: @ "Accept"]; [self setImageWithURLRequest: request placeholderImage: placeholderImage success: nil failure: nil];}

 

 
// The Key to internal implementation is to determine whether the image corresponding to this url exists in the single-instance cache class. (Note that the internal implementation is to obtain the image in the cache. If no image is available, the image is actually unavailable ), if it exists, it is directly returned to the outside. If it does not exist, it is obtained through a url request and then stored in the cache (saved to the cache)-(void) setImageWithURLRequest (NSURLRequest *) urlRequest placeholderImage :( UIImage *) placeholderImage success :( void (^) (NSURLRequest * request, response * response, UIImage * image) success failure :( void (^) (NSURLRequest * request, response * response, NSError * error) failure {[self defined]; UIImage * cachedImage = [[self class] nvidimagecache] cachedImageForRequest: urlRequest]; // obtain if (cachedImage) {if (success) {success (nil, nil, cachedImage);} else {self. image = cachedImage;} self. af_imageRequestOperation = nil;} else {if (placeholderImage) {self. image = placeholderImage;} _ weak _ typeof (self) weakSelf = self; self. af_imageRequestOperation = [[AFHTTPRequestOperation alloc] initWithRequest: urlRequest]; self. af_imageRequestOperation.responseSerializer = self. imageResponseSerializer; [self. af_imageRequestOperation failed: ^ (AFHTTPRequestOperation * operation, id responseObject) {_ strong _ typeof (weakSelf) strongSelf = weakSelf; if ([[urlRequest URL] isEqual: [strongSelf. af_imageRequestOperation.request URL]) {if (success) {success (urlRequest, operation. response, responseObject);} else if (responseObject) {strongSelf. image = responseObject;} if (operation = strongSelf. af_imageRequestOperation) {strongSelf. handler = nil ;}[ [[strongSelf class] nvidimagecache] cacheImage: responseObject forRequest: urlRequest]; // saved} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {_ strong _ typeof (weakSelf) strongSelf = weakSelf; if ([urlRequest URL] isEqual: [strongSelf. af_imageRequestOperation.request URL]) {if (failure) {failure (urlRequest, operation. response, error);} if (operation = strongSelf. af_imageRequestOperation) {strongSelf. af_imageRequestOperation = nil ;}}]; [[self class] af_nvidimagerequestoperationqueue] addOperation: self. af_imageRequestOperation] ;}}- (void) cancelImageRequestOperation {[self. af_imageRequestOperation cancel]; self. af_imageRequestOperation = nil;} @ end # pragma mark-static inline NSString * AFImageCacheKeyFromURLRequest (NSURLRequest * request) {return [[request URL] absoluteString];} @ implementation AFImageCache
// Cache implementation is achieved through the following two methods-(UIImage *) cachedImageForRequest :( NSURLRequest *) request {switch ([request cachePolicy]) {case NSURLRequestReloadIgnoringCacheData: case when: return nil; default: break;} return [self objectForKey: AFImageCacheKeyFromURLRequest (request)];}-(void) cacheImage :( UIImage *) image forRequest :( NSURLRequest *) request {if (image & request) {[self setObject: image forKey: AFImageCacheKeyFromURLRequest (request)] ;}}@ end # endif
The above cache comes with AF

 

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.