iOS三方应用iOS基础知识

SDWebImage之缓存策略

2020-12-22  本文已影响0人  小篆风

目录

简介

本章节只是对SDWebImage中内存策略一块的理解。

取值 - 内存缓存

1、从内存缓存中取值首先会判读类型不等与SDImageCacheTypeDisk磁盘缓存

//SDImageCache
- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context cacheType:(SDImageCacheType)queryCacheType done:(nullable SDImageCacheQueryCompletionBlock)doneBlock {
...
//memory内存缓存取值
  UIImage *image;
  if (queryCacheType != SDImageCacheTypeDisk) {
      image = [self imageFromMemoryCacheForKey:key];
  }
...

}

2、从self.memoryCache中取值,key是url

//SDImageCache
- (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key {
   return [self.memoryCache objectForKey:key];
}

3、self.memoryCache是SDMemoryCache类型,SDMemoryCache是NSCache类型。

//SDImageCache
@property (nonatomic, strong, readonly, nonnull) id<SDMemoryCache> memoryCache;

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

//SDMemoryCache
@property (nonatomic, strong, nonnull, readonly) SDImageCacheConfig *config;

@end

取值-磁盘取值

//SDImageCache
- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context cacheType:(SDImageCacheType)queryCacheType done:(nullable SDImageCacheQueryCompletionBlock)doneBlock {
  ...
    //disk磁盘取值
    1、从self.diskCache中取diskData
        @autoreleasepool {
          //从self.diskCache中取diskData
            NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key];
            UIImage *diskImage;
            SDImageCacheType cacheType = SDImageCacheTypeNone;
            if (image) {
                // the image is from in-memory cache, but need image data
                diskImage = image;
                cacheType = SDImageCacheTypeMemory;
            } else if (diskData) {
                cacheType = SDImageCacheTypeDisk;
                // decode image data only if in-memory cache missed
                diskImage = [self diskImageForKey:key data:diskData options:options context:context];
                if (diskImage && self.config.shouldCacheImagesInMemory) {
                    NSUInteger cost = diskImage.sd_memoryCost;
                    [self.memoryCache setObject:diskImage forKey:key cost:cost];
                }
            }
            
            if (doneBlock) {
                if (shouldQueryDiskSync) {
                    doneBlock(diskImage, diskData, cacheType);
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        doneBlock(diskImage, diskData, cacheType);
                    });
                }
            }
        }
...
}

1、从self.diskCache中取diskData

//SDImageCache
 - (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key {
    ...
    NSData *data = [self.diskCache dataForKey:key];
    ...
}

2、self.diskCache类型为SDDiskCache

//SDImageCache
@property (nonatomic, strong, readonly, nonnull) id<SDDiskCache> diskCache;

3、SDDiskCache磁盘缓存是用NSFileManager实现的

@property (nonatomic, strong, nonnull) NSFileManager *fileManager;

- (NSData *)dataForKey:(NSString *)key {
    NSParameterAssert(key);
    NSString *filePath = [self cachePathForKey:key];
    NSData *data = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil];
    if (data) {
        return data;
    }
    
    // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
    // checking the key with and without the extension
    data = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension options:self.config.diskCacheReadingOptions error:nil];
    if (data) {
        return data;
    }
    
    return nil;
}
- (void)setData:(NSData *)data forKey:(NSString *)key {
    NSParameterAssert(data);
    NSParameterAssert(key);
    if (![self.fileManager fileExistsAtPath:self.diskCachePath]) {
        [self.fileManager createDirectoryAtPath:self.diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    // get cache Path for image key
    NSString *cachePathForKey = [self cachePathForKey:key];
    // transform to NSUrl
    NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey];
    
    [data writeToURL:fileURL options:self.config.diskCacheWritingOptions error:nil];
    
    // disable iCloud backup
    if (self.config.shouldDisableiCloud) {
        // ignore iCloud backup resource value error
        [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
    }
}

存值-内存缓存

//SDWebImageManager
- (void)callCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
                                 url:(nonnull NSURL *)url
                             options:(SDWebImageOptions)options
                             context:(nullable SDWebImageContext *)context
                            progress:(nullable SDImageLoaderProgressBlock)progressBlock
                           completed:(nullable SDInternalCompletionBlock)completedBlock {
  ...
    operation.cacheOperation = [imageCache queryImageForKey:key options:options context:context cacheType:queryCacheType completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) {
  //优先从缓存中获取,如果没有获取到再请求获取
    ...
    [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:cachedImage cachedData:cachedData cacheType:cacheType progress:progressBlock completed:completedBlock];
    ...
  }
  ...
}

2、创建loaderOperation <SDWebImageOperation>下载任务

//SDWebImageDownloader
- (void)callDownloadProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
                                    url:(nonnull NSURL *)url
                                options:(SDWebImageOptions)options
                                context:(SDWebImageContext *)context
                            cachedImage:(nullable UIImage *)cachedImage
                             cachedData:(nullable NSData *)cachedData
                              cacheType:(SDImageCacheType)cacheType
                               progress:(nullable SDImageLoaderProgressBlock)progressBlock
                              completed:(nullable SDInternalCompletionBlock)completedBlock {
  ...
//2、创建loaderOperation <SDWebImageOperation>下载任务
  operation.loaderOperation = [imageLoader requestImageWithURL:url options:options context:context progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) {

      ...
      // Continue store cache process
      [self callStoreCacheProcessForOperation:operation url:url options:options context:context downloadedImage:downloadedImage downloadedData:downloadedData finished:finished progress:progressBlock completed:completedBlock];
      ...
  }
  ...
}

3、下载之后,进行缓存

//SDImageCache
- (void)storeImage:(nullable UIImage *)image
         imageData:(nullable NSData *)imageData
            forKey:(nullable NSString *)key
          toMemory:(BOOL)toMemory
            toDisk:(BOOL)toDisk
        completion:(nullable SDWebImageNoParamsBlock)completionBlock {
    if (!image || !key) {
        if (completionBlock) {
            completionBlock();
        }
        return;
    }
    // if memory cache is enabled
    //3.1:如果满足内存缓存条件,则进行内存缓存
    if (toMemory && self.config.shouldCacheImagesInMemory) {
        NSUInteger cost = image.sd_memoryCost;
        [self.memoryCache setObject:image forKey:key cost:cost];
    }
    //3.2:如果满足磁盘缓存条件,则进行缓存缓存
    if (toDisk) {
          dispatch_async(self.ioQueue, ^{
                ......
          })
    }
}
image.png

缓存策略整体流程:
1、每次加载图片优先取缓存中取
2、如果memory有,则直接返回
3、如果memory没有,则到disk中取
4、如果disk有,则对内存添加一份
5、如果disk没有,则进行网络请求加载
6、加载完成之后,对memory和disk各存一份。

面试题

1、SDWebImage 的最大并发数是多少,默认超时时间是多少

//SDWebImageDownloaderConfig
- (instancetype)init {
    self = [super init];
    if (self) {
        _maxConcurrentDownloads = 6;
        _downloadTimeout = 15.0;
        _executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
    }
    return self;
}

最大并发数6,默认超时时间15.0秒,外部可以修改

2、SDWebImage 缓存技术是什么

//SDMemoryCache
@interface SDMemoryCache <KeyType, ObjectType> : NSCache <KeyType, ObjectType> <SDMemoryCache>
@property (nonatomic, strong, nonnull, readonly) SDImageCacheConfig *config;
@end

//self.diskCache类型为SDDiskCache
@property (nonatomic, strong, nonnull) NSFileManager *fileManager;

- (NSData *)dataForKey:(NSString *)key {}
- (void)setData:(NSData *)data forKey:(NSString *)key {}

内存缓存使用NSCache
磁盘缓存使用NSFileManager
内存管理使用NSCache

3、SDWebImage的Disk删除时机
3.1:SDImageCache类还监听了UIApplicationDidReceiveMemoryWarningNotification通知,当收到内存警告时候清除Memory缓存

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveMemoryWarning:)
                                                 name:UIApplicationDidReceiveMemoryWarningNotification
                                               object:nil];
#endif
}

// Current this seems no use on macOS (macOS use virtual memory and do not clear cache when memory warning). So we only override on iOS/tvOS platform.
#if SD_UIKIT
- (void)didReceiveMemoryWarning:(NSNotification *)notification {
    // Only remove cache, but keep weak cache
    [super removeAllObjects];
}

3.2:图片默认缓存时间是一周

//SDImageCacheConfig
static const NSInteger kDefaultCacheMaxDiskAge = 60 * 60 * 24 * 7; // 1 week

【参考】

https://juejin.cn/post/6844903598401273870

上一篇下一篇

猜你喜欢

热点阅读