AFNetworking 3.0 源碼解讀(七)之 AFAutoPurgingImageCache

這篇我們就要介紹AFAutoPurgingImageCache這個(gè)類了。這個(gè)類給了我們臨時(shí)管理圖片內(nèi)存的能力。

前言

假如說我們要寫一個(gè)通用的網(wǎng)絡(luò)框架,除了必備的請求數(shù)據(jù)的方法外,必須提供一個(gè)下載器來管理應(yīng)用內(nèi)的所有的下載事件。至于下載器能夠提供的功能,在此先不做說明。但在 AFAutoPurgingImageCache 中我們能夠借鑒一些東西。

AFImageCache

通過這個(gè)協(xié)議,我們能夠做下邊四件事:


AFImageRequestCache

這個(gè)協(xié)議繼承自AFImageCache,然后又?jǐn)U展了下邊三個(gè)方法:


AFAutoPurgingImageCache

它集成了AFImageRequestCache協(xié)議,因此上圖中的方法都會(huì)實(shí)現(xiàn)。我們先看看它暴露出來的有哪些東西:

  1. UInt64 memoryCapacity 總共的內(nèi)存容量
  2. UInt64 preferredMemoryUsageAfterPurge 當(dāng)清空時(shí)優(yōu)先保存的容量
  3. UInt64 memoryUsage 當(dāng)前已使用的容量
  4. init 初始化方法
  5. initWithMemoryCapacity: preferredMemoryCapacity: 初始化方法

AFCachedImage

AFCachedImage用來抽象被緩存的圖片,看到這個(gè)對象,我聯(lián)想到一個(gè)下載器也需要一個(gè)這樣的被下載的對象的抽象描述類。我們需要一些屬性來描述這個(gè)被緩存的圖片。

  1. UIImage *image 圖片
  2. NSString *identifier 標(biāo)識
  3. UInt64 totalBytes 總大小,已字節(jié)為單位
  4. NSDate *lastAccessDate 最后的訪問時(shí)間,用于清理內(nèi)存時(shí),進(jìn)行排序
  5. UInt64 currentMemoryUsage 當(dāng)前的容量使用情況

--

-(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);
        
        // 每個(gè)像素占用4個(gè)字節(jié)
        CGFloat bytesPerPixel = 4.0;
        //這個(gè)是指圖片中有多少個(gè)像素,這個(gè)名稱bytesPerSize改為pixelsPerSize是不是更加貼切呢?
        CGFloat bytesPerSize = imageSize.width * imageSize.height;
        self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize;
        self.lastAccessDate = [NSDate date];
    }
    return self;
}

--

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

- (NSString *)description {
    NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@  lastAccessDate: %@ ", self.identifier, self.lastAccessDate];
    return descriptionString;

}

AFAutoPurgingImageCache實(shí)現(xiàn)部分

既然是圖片的臨時(shí)緩存類,那么我們應(yīng)該把圖片緩存到什么地方呢?答案就是一個(gè)字典中。值得注意的是,我們緩存使用的是一個(gè)同步的隊(duì)列 。

  1. NSMutableDictionary <NSString* , AFCachedImage*> *cachedImages 存放圖片
  2. UInt64 currentMemoryUsage 當(dāng)前使用的容量
  3. dispatch_queue_t synchronizationQueue 隊(duì)列

--

- (instancetype)init {
    return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024];
}

通過這個(gè)方法,我們就能夠看出默認(rèn)的緩存容量的大小為100M,清除后保存容量為60M

- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity {
    if (self = [super init]) {
        self.memoryCapacity = memoryCapacity;
        self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity;
        self.cachedImages = [[NSMutableDictionary alloc] init];

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

        [[NSNotificationCenter defaultCenter]
         addObserver:self
         selector:@selector(removeAllImages)
         name:UIApplicationDidReceiveMemoryWarningNotification
         object:nil];

    }
    return self;
}

--

- (UInt64)memoryUsage {
    __block UInt64 result = 0;
    dispatch_sync(self.synchronizationQueue, ^{
        result = self.currentMemoryUsage;
    });
    return result;
}

--

- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier {
    dispatch_barrier_async(self.synchronizationQueue, ^{
        AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier];

        AFCachedImage *previousCachedImage = self.cachedImages[identifier];
        if (previousCachedImage != nil) {
            self.currentMemoryUsage -= previousCachedImage.totalBytes;
        }

        self.cachedImages[identifier] = cacheImage;
        self.currentMemoryUsage += cacheImage.totalBytes;
    });

    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;

            for (AFCachedImage *cachedImage in sortedImages) {
                [self.cachedImages removeObjectForKey:cachedImage.identifier];
                bytesPurged += cachedImage.totalBytes;
                if (bytesPurged >= bytesToPurge) {
                    break ;
                }
            }
            self.currentMemoryUsage -= bytesPurged;
        }
    });
}

這個(gè)方法是核心方法,我們重點(diǎn)介紹下,在這個(gè)方法中,一共做了兩件事:

  1. 把圖片加入到緩存字典中(注意字典中可能存在identifier的情況),然后計(jì)算當(dāng)前的容量大小
  2. 處理容量超過最大容量的異常情況。分為下邊幾個(gè)步驟: 1.比較容量是否超過最大容量 2.計(jì)算將要清楚的緩存容量 3.把所有緩存的圖片放到一個(gè)數(shù)組中 4.對這個(gè)數(shù)組按照最后訪問時(shí)間進(jìn)行排序,優(yōu)先保留最后訪問的數(shù)據(jù) 5.遍歷數(shù)組,移除圖片(當(dāng)已經(jīng)移除的數(shù)據(jù)大于應(yīng)該移除的數(shù)據(jù)時(shí)停止)

<font color=orange>ps: </font> 這里不得不講一下 dispatch_barrier_async 這個(gè)方法。barrier 這個(gè)單詞的意思是障礙,攔截的意思,也即是說dispatch_barrier_async一定是有攔截事件的作用。

看下邊這段代碼:

 dispatch_queue_t concurrentQueue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(concurrentQueue, ^(){
        NSLog(@"dispatch-1");
    });
    dispatch_async(concurrentQueue, ^(){
        NSLog(@"dispatch-2");
    });
    dispatch_barrier_async(concurrentQueue, ^(){
        NSLog(@"dispatch-barrier");
    });
    dispatch_async(concurrentQueue, ^(){
        NSLog(@"dispatch-3");
    });
    dispatch_async(concurrentQueue, ^(){
        NSLog(@"dispatch-4");
    });

打印結(jié)果:

2016-08-22 16:43:20.554 xxx[26805:271426] dispatch-1
2016-08-22 16:43:20.555 xxx[26805:271422] dispatch-2
2016-08-22 16:43:20.556 xxx[26805:271422] dispatch-barrier
2016-08-22 16:43:20.556 xxx[26805:271422] dispatch-3
2016-08-22 16:43:20.556 xxx[26805:271426] dispatch-4

這個(gè)說明了dispatch_barrier_async能夠攔截它前邊的異步事件,等待兩個(gè)異步方法都完成之后,調(diào)用dispatch_barrier_async。

我們稍微改動(dòng)一下:

dispatch_queue_t concurrentQueue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(concurrentQueue, ^(){
    NSLog(@"dispatch-1");
});
dispatch_async(concurrentQueue, ^(){
    NSLog(@"dispatch-2");
});
dispatch_barrier_sync(concurrentQueue, ^(){
    NSLog(@"dispatch-barrier");
});
dispatch_async(concurrentQueue, ^(){
    NSLog(@"dispatch-3");
});
dispatch_async(concurrentQueue, ^(){
    NSLog(@"dispatch-4");
});

打印結(jié)果:

2016-08-22 16:43:20.554 xxx[26805:271426] dispatch-1
2016-08-22 16:43:20.555 xxx[26805:271422] dispatch-2
2016-08-22 16:43:20.556 xxx[26805:271422] dispatch-barrier
2016-08-22 16:43:20.556 xxx[26805:271422] dispatch-3
2016-08-22 16:43:20.556 xxx[26805:271426] dispatch-4

--

- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier {
    NSString *key = request.URL.absoluteString;
    if (additionalIdentifier != nil) {
        key = [key stringByAppendingString:additionalIdentifier];
    }
    return key;
}

通過這個(gè)方法可以看出,使用NSURLRequest進(jìn)行緩存的時(shí)候,也只是使用了request.URL.absoluteString + additionalIdentifier 來作為緩存字典的key。在這里其他協(xié)議的實(shí)現(xiàn)方法就不做介紹了。

總結(jié)

通過這個(gè)文件,提供給了我們一個(gè)關(guān)于下載器 下載后的文件的一個(gè)封裝的思路。按照正常來說,下載后的文件的標(biāo)識應(yīng)該就是URL。

推薦閱讀

AFNetworking 3.0 源碼解讀(一)之 AFNetworkReachabilityManager

AFNetworking 3.0 源碼解讀(二)之 AFSecurityPolicy

AFNetworking 3.0 源碼解讀(三)之 AFURLRequestSerialization

AFNetworking 3.0 源碼解讀(四)之 AFURLResponseSerialization

AFNetworking 3.0 源碼解讀(五)之 AFURLSessionManager

AFNetworking 3.0 源碼解讀(六)之 AFHTTPSessionManager

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容