美文网首页
AFNetworking 3.0 源码解读之 AFAutoPur

AFNetworking 3.0 源码解读之 AFAutoPur

作者: colacola | 来源:发表于2018-01-29 08:54 被阅读26次

    之前在UIImageView提到,在开启图片下载任务之前,会先查找缓存中是否有该图片。

    //5、如果图片缓存存在,就使用该缓存图片 Use the image from the image cache if it exists
        UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
    

    查找缓存图片的这个方法- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier 来自AFAutoPurgingImageCache这个类。
    在AFAutoPurgingImageCache的.h文件中申明了协议AFImageCache。

    /**
     The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously.
     */
    

    AFImageCache 这个协议有以下4个功能。


    image.png

    还有一个协议AFImageRequestCache,它继承自AFImageCache,又扩展了3个方法。


    image.png

    在AFAutoPurgingImageCache的.m文件中申明了AFCachedImage。

    @interface AFCachedImage : NSObject
    
    @property (nonatomic, strong) UIImage *image;
    @property (nonatomic, strong) NSString *identifier; //图片标识符
    @property (nonatomic, assign) UInt64 totalBytes;//图片总大小
    @property (nonatomic, strong) NSDate *lastAccessDate;//最近访问时间
    @property (nonatomic, assign) UInt64 currentMemoryUsage; // 当前内存容量
    
    @end
    

    而AFAutoPurgingImageCache的属性中,有一个存放AFCachedImage对象的字典cachedImages。
    注意一下,在AFNetworking中,缓存的图片是放在NSMutableDictionary的可变字典中的,不像SDWebImage那样,有做2层缓存处理。

    @interface AFAutoPurgingImageCache ()
    @property (nonatomic, strong) NSMutableDictionary <NSString* , AFCachedImage*> *cachedImages;
    @property (nonatomic, assign) UInt64 currentMemoryUsage;
    @property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
    @end
    

    了解了AFAutoPurgingImageCache的基本信息,下面倒着来看下这个缓存的方法。

    - (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
        return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
    }
    

    这个方法,又是通过图片的identifier来寻找的。
    再看这个imageWithIdentifier方法

    - (nullable UIImage *)imageWithIdentifier:(NSString *)identifier {
        __block UIImage *image = nil;
        dispatch_sync(self.synchronizationQueue, ^{
            AFCachedImage *cachedImage = self.cachedImages[identifier];
            image = [cachedImage accessImage];
        });
        return image;
    }
    

    并行队列 synchronizationQueue中,读取图片。

    NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]];
            self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
    

    此时,cachedImages这个字典派上用场了,通过identifier这个key,寻找对应的AFCachedImage类型的缓存图片。然后通过AFCachedImage类中的accessImage方法,先设置lastAccessDate最新访问的时间为最新时间,再将属性中存储的image返回。

    - (UIImage*)accessImage {
        self.lastAccessDate = [NSDate date];
        return self.image;
    }
    

    那这个self.image是怎么来的呢?
    再继续往前找,AFCachedImage声明了一个初始化的方法

    @implementation AFCachedImage
    
    -(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier {
        if (self = [self init]) {
            self.image = image;
            self.identifier = identifier;
    
            CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
            CGFloat bytesPerPixel = 4.0;
            CGFloat bytesPerSize = imageSize.width * imageSize.height;
            self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize;
            self.lastAccessDate = [NSDate date];
        }
        return self;
    }
    

    这个方法里初始化了AFCachedImage的4个属性,分别是图片image,标识符identifier,totalBytes总大小(字节为单位),lastAccessDate最新访问时间(用于清理内存时,进行排序)。
    这个初始化,在AFAutoPurgingImageCache类中,添加图片的方法里会用到。

    - (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier {
        //注意,这里使用了dispatch_barrier_async,相当于把block( ^{})中的任务排在了这个并行队列后面,
        dispatch_barrier_async(self.synchronizationQueue, ^{
       1、先是通过image和identifier初始化一个AFCachedImage
            AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier];
      2、然后通过identifier找到cachedImages中保存的对应对象previousCachedImage
            AFCachedImage *previousCachedImage = self.cachedImages[identifier];
    3、根据currentMemoryUsage是否存在重新计算currentMemoryUsage。
            if (previousCachedImage != nil) {
                self.currentMemoryUsage -= previousCachedImage.totalBytes;
            }
    
            self.cachedImages[identifier] = cacheImage;
            self.currentMemoryUsage += cacheImage.totalBytes;
        });
    4、另外一个dispatch_barrier_async中,通过currentMemoryUsage和memoryCapacity大小对比,将之前保存的缓存图片数组根据lastAccessDate排序。使用了LRU缓存策略。
        dispatch_barrier_async(self.synchronizationQueue, ^{
            if (self.currentMemoryUsage > self.memoryCapacity) {
                UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge;
                NSMutableArray <AFCachedImage*> *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues];
                NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate"
                                                                               ascending:YES];
                [sortedImages sortUsingDescriptors:@[sortDescriptor]];
    
                UInt64 bytesPurged = 0;
    5、将重新排序的数组,遍历数组,移除数据直到缓存容量小于等于限值
                for (AFCachedImage *cachedImage in sortedImages) {
                    [self.cachedImages removeObjectForKey:cachedImage.identifier];
                    bytesPurged += cachedImage.totalBytes;
                    if (bytesPurged >= bytesToPurge) {
                        break ;
                    }
                }
                self.currentMemoryUsage -= bytesPurged;
            }
        });
    }
    

    “这个方法是核心方法,在这个方法中,一共做了两件事:

    把图片加入到缓存字典中(注意字典中可能存在identifier的情况),然后计算当前的容量大小
    处理容量超过最大容量的异常情况。分为下边几个步骤: 1.比较容量是否超过最大容量 2.计算将要清楚的缓存容量 3.把所有缓存的图片放到一个数组中 4.对这个数组按照最后访问时间进行排序,优先保留最后访问的数据 5.遍历数组,移除图片(当已经移除的数据大于应该移除的数据时停止)”

    参考文章:
    AFNetworking 3.0 源码解读(七)之 AFAutoPurgingImageCache

    相关文章

      网友评论

          本文标题:AFNetworking 3.0 源码解读之 AFAutoPur

          本文链接:https://www.haomeiwen.com/subject/vgwtzxtx.html