SDWebImage源碼分析

SDWebImage

先看一張官方圖:


image.png

UIImageView ---->

UIImageView (WebCache)

[self sd_internalSetImageWithURL:url
                placeholderImage:placeholder
                         options:options
                    operationKey:nil
                   setImageBlock:nil
                        progress:progressBlock
                       completed:completedBlock];

UIView (WebCache)

  • (void)sd_internalSetImageWithURL:(nullable NSURL *)url
    placeholderImage:(nullable UIImage *)placeholder
    options:(SDWebImageOptions)options
    operationKey:(nullable NSString *)operationKey
    setImageBlock:(nullable SDSetImageBlock)setImageBlock
    progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
    completed:(nullable SDExternalCompletionBlock)completedBlock
    context:(nullable NSDictionary<NSString *, id> *)context {
    [self sd_cancelImageLoadOperationWithKey:validOperationKey]
    取消當(dāng)前UI空間的下載operation
    [self sd_cancelImageLoadOperationWithKey:validOperationKey];

拿到 [SDWebImageManager sharemanager]
去manager里面去loadImageWithURL查找緩存

SDWebImageManager

manager = [SDWebImageManager sharedManager];

---->[圖片上傳失敗...(image-84f965-1586670613002)]

- (id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
                                     options:(SDWebImageOptions)options
                                    progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                   completed:(nullable SDInternalCompletionBlock)completedBlock ;

SDMemoryCache <KeyType, ObjectType> ()

---->
去緩存查找,cache,disk

(nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options done:(nullable SDCacheQueryCompletedBlock)doneBlock

通過SDImageCache 去查找緩存
key = url cache 通過 url為key(默認(rèn)url為key,也可以自定義cacheKeyFilter block) 去查找緩存
disk 是通過url MD5之后加上路徑去獲取data 查找圖片

[self imageFromMemoryCacheForKey:key]
[self defaultCachePathForKey:key]

key ->  diskCachePath/[url md5]
/Users/tangyj/Library/Developer/CoreSimulator/Devices/EB0F9D20-942D-4321-9C85-7D0F6895F7DB/data/Containers/Data/Application/3EFE64DF-FC1A-4CB9-BF0C19F86295C861/Library/Caches/default/com.hackemist.SDWebImageCache.default/e8ef725f48e22570c3befecc91d75aa9.png

如果緩存沒找到,或者options是SDWebImageRefreshCached類型,非SDWebImageFromCacheOnly

SDWebImageDownloader

核心代碼 創(chuàng)建了session,添加了operation 到downloadQueue 中,downloadQueue的maxOperations = 6

self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration
                                                 delegate:self
                                            delegateQueue:nil];
     [self.URLOperations setObject:operation forKey:url];
        // Add operation to operation queue only after all configuration done according to Apple's doc.
        // `addOperation:` does not synchronously execute the `operation.completionBlock` so this will not cause deadlock.
        [self.downloadQueue addOperation:operation];

去下載SDWebImageDownloader *imageDownloader

[SDWebImageCombinedOperation new] --- cacheOperation / downloadToken
            strongOperation.downloadToken = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished);

[self addProgressCallback:progressBlock completedBlock:completedBlock forURL:url createCallback:^SDWebImageDownloaderOperation *{
if (timeoutInterval == 0.0) {
            timeoutInterval = 15.0;
        }
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url
                                                                    cachePolicy:cachePolicy
                                                                timeoutInterval:timeoutInterval];
        SDWebImageDownloaderOperation *operation = [[sself.operationClass alloc] initWithRequest:request inSession:sself.session options:options];
        operation.shouldDecompressImages = sself.shouldDecompressImages;

}

如果NSURLSessionDataDelegate執(zhí)行會偷傳給SDWebImageDownloaderOperation 的代理方法。

//#pragma mark NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {

SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask];
    if ([dataOperation respondsToSelector:@selector(URLSession:dataTask:didReceiveResponse:completionHandler:)]) {
        [dataOperation URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler];
    }

SDWebImageDownloaderOperation : NSOperation

//self.callbackBlocks 里面存放progressBlock,completedBlock

SDCallbacksDictionary*callbacks = [NSMutableDictionary new];
    if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
    if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
    LOCK(self.callbacksLock);
    [self.callbackBlocks addObject:callbacks];
    UNLOCK(self.callbacksLock);

// 如果沒有session創(chuàng)建session,一般download會傳過來

if(!session){
            session = [NSURLSession sessionWithConfiguration:sessionConfig
                                                    delegate:self
                                               delegateQueue:nil];
            self.ownedSession = session;
            }
            // 創(chuàng)建datatask
        self.dataTask = [session dataTaskWithRequest:self.request];
//下載完成
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    NSArray<id> *completionBlocks = [self callbacksForKey:kCompletedCallbackKey];
            completedBlock(image, imageData, error, finished);
            }

@interface SDWebImageDownloadToken ()

@property (nonatomic, weak, nullable) NSOperation<SDWebImageDownloaderOperationInterface> *downloadOperation;

@end
這個類作為downloader 的返回值

SDImageCache 單例

/**

  • Cache Config object - storing all kind of settings
    */
    @property (nonatomic, nonnull, readonly) SDImageCacheConfig *config;

/**

  • The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory.
    */
    @property (assign, nonatomic) NSUInteger maxMemoryCost;

/**

  • The maximum number of objects the cache should hold.
    */
    @property (assign, nonatomic) NSUInteger maxMemoryCountLimit;

里面主要有一個SDMemoryCache,繼承NSCache,不過自身又存了一個maptable,
NSMapTable(strong key,weak value)的hashtable,NSCache本身存儲不穩(wěn)定,內(nèi)存緊張的時候會自己釋放對象,不大可控

@property (strong, nonatomic, nonnull) SDMemoryCache *memCache;

@interface SDMemoryCache <KeyType, ObjectType> : NSCache <KeyType, ObjectType>

@interface SDMemoryCache <KeyType, ObjectType> ()

@property (nonatomic, strong, nonnull) NSMapTable<KeyType, ObjectType> *weakCache; // strong-weak cache
@property (nonatomic, strong, nonnull) dispatch_semaphore_t weakCacheLock; // a lock to keep the access to `weakCache` thread-safe
@end
    self.weakCache = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
- (void)setObject:(id)obj forKey:(id)key cost:(NSUInteger)g {
    [super setObject:obj forKey:key cost:g];
    if (key && obj) {
        // Store weak cache
        LOCK(self.weakCacheLock);
        [self.weakCache setObject:obj forKey:key];
        UNLOCK(self.weakCacheLock);
    }
}
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(deleteOldFiles)
                                                 name:UIApplicationWillTerminateNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(backgroundDeleteOldFiles)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];

進入后臺和將要推出 deleteOldFilesWithCompletionBlock
刪除 比設(shè)定時間久的文件,默認(rèn)是7天有效期
for (NSURL *fileURL in urlsToDelete) {
[self.fileManager removeItemAtURL:fileURL error:nil];
}

設(shè)置過預(yù)期maxCacheSize的,如果當(dāng)前size大于預(yù)期,按照修改添加日期排序,從oldest開始刪除,刪除到預(yù)期maxCacheSize的一半為止。

    if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) {
        // Target half of our maximum cache size for this cleanup pass.
        const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2;

    // If our remaining disk cache exceeds a configured maximum size, perform a second
    // size-based cleanup pass.  We delete the oldest files first.
    if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) {
        // Target half of our maximum cache size for this cleanup pass.
        const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2;

        // Sort the remaining cache files by their last modification time (oldest first).
        NSArray<NSURL *> *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
                                                                 usingComparator:^NSComparisonResult(id obj1, id obj2) {
                                                                     return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
                                                                 }];

        // Delete files until we fall below our desired cache size.
        for (NSURL *fileURL in sortedFiles) {
        if ([self.fileManager removeItemAtURL:fileURL error:nil]) {
            NSDictionary<NSString *, id> *resourceValues = cacheFiles[fileURL];
            NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
            currentCacheSize -= totalAllocatedSize.unsignedIntegerValue;

            if (currentCacheSize < desiredCacheSize) {
                break;
            }
        }
    }
}
if (completionBlock) {
    dispatch_async(dispatch_get_main_queue(), ^{
        completionBlock();
    });
}

});

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

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

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