该文章阅读的AFNetworking的版本为3.2.0。缓存
AFAutoPurgingImageCache
该类是用来管理内存中图片的缓存。bash
这个协议定义了一些对缓存中图片增删查的同步操做并发
/**
以指定的标识符向缓存中添加图片
*/
- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier;
/**
移除缓存中指定标识符的图片
*/
- (BOOL)removeImageWithIdentifier:(NSString *)identifier;
/**
移除缓存中全部的图片
*/
- (BOOL)removeAllImages;
/**
获取缓存中指定标识符的图片
*/
- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier;
复制代码
这个协议继承了AFImageCache
协议,扩展了增删查的方法async
/**
询问是否能以指定的请求和附加标识符来缓存图像。
*/
- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
以指定的请求和附加标识符向缓存中添加图片
*/
- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
移除缓存中指定的请求和附加标识符的图片
*/
- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
获取缓存中指定的请求和附加标识符的图片
*/
- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
复制代码
/**
用来缓存的总的内存容量
*/
@property (nonatomic, assign) UInt64 memoryCapacity;
/**
清除缓存时应当保留的缓存容量
*/
@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge;
/**
当前缓存已经用掉的容量
*/
@property (nonatomic, assign, readonly) UInt64 memoryUsage;
复制代码
/**
初始化方法,默认总容量为100M,保留容量为60M
*/
- (instancetype)init;
/**
初始化方法,自定义总容量和保留容量
*/
- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity;
复制代码
这个类是用来描述被缓存的图片ide
/**
被缓存的图片
*/
@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;
复制代码
-(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier {
if (self = [self init]) {
// 属性保存参数
self.image = image;
self.identifier = identifier;
// 获取图片的像素尺寸,并以每像素4字节计算图片大小
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;
}
- (UIImage*)accessImage {
// 记录获取被缓存的图片的时间
self.lastAccessDate = [NSDate date];
return self.image;
}
- (NSString *)description {
// 定制打印数据
NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate];
return descriptionString;
}
复制代码
/**
用可变字典保存缓存图片
*/
@property (nonatomic, strong) NSMutableDictionary <NSString* , AFCachedImage*> *cachedImages;
/**
当前内存使用量
*/
@property (nonatomic, assign) UInt64 currentMemoryUsage;
/**
同步队列
*/
@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
复制代码
- (instancetype)init {
// 调用下面的方法
return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024];
}
- (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;
}
- (void)dealloc {
// 移除通知监听
[[NSNotificationCenter defaultCenter] removeObserver: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对象
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];
// 设置排序描述对象为按照属性lastAccessDate的升序排列
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;
}
});
}
- (BOOL)removeImageWithIdentifier:(NSString *)identifier {
__block BOOL removed = NO;
dispatch_barrier_sync(self.synchronizationQueue, ^{
// 获取到指定标识符的图片缓存对象
AFCachedImage *cachedImage = self.cachedImages[identifier];
if (cachedImage != nil) {
// 若是有这张图片就从缓存中删除并从新计算当前内存使用量
[self.cachedImages removeObjectForKey:identifier];
self.currentMemoryUsage -= cachedImage.totalBytes;
removed = YES;
}
});
return removed;
}
- (BOOL)removeAllImages {
__block BOOL removed = NO;
dispatch_barrier_sync(self.synchronizationQueue, ^{
if (self.cachedImages.count > 0) {
// 删除全部图片缓存并置零内存使用量
[self.cachedImages removeAllObjects];
self.currentMemoryUsage = 0;
removed = YES;
}
});
return removed;
}
- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier {
__block UIImage *image = nil;
dispatch_sync(self.synchronizationQueue, ^{
// 获取到指定标识符的图片缓存对象
AFCachedImage *cachedImage = self.cachedImages[identifier];
image = [cachedImage accessImage];
});
return image;
}
复制代码
- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
// 用request和identifier生成一个新标识符后添加图片
[self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
// 移除用request和identifier生成一个新标识符的图片
return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
// 获取用request和identifier生成一个新标识符的图片
return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier {
// 将标识符拼在请求连接后面组成字符串
NSString *key = request.URL.absoluteString;
if (additionalIdentifier != nil) {
key = [key stringByAppendingString:additionalIdentifier];
}
return key;
}
- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier {
// 只返回YES
return YES;
}
复制代码
源码阅读系列:AFNetworkingpost
源码阅读:AFNetworking(二)——AFURLRequestSerializationatom
源码阅读:AFNetworking(三)——AFURLResponseSerializationspa
源码阅读:AFNetworking(四)——AFSecurityPolicy3d
源码阅读:AFNetworking(五)——AFNetworkReachabilityManager
源码阅读:AFNetworking(六)——AFURLSessionManager
源码阅读:AFNetworking(七)——AFHTTPSessionManager
源码阅读:AFNetworking(八)——AFAutoPurgingImageCache
源码阅读:AFNetworking(九)——AFImageDownloader
源码阅读:AFNetworking(十)——AFNetworkActivityIndicatorManager
源码阅读:AFNetworking(十一)——UIActivityIndicatorView+AFNetworking
源码阅读:AFNetworking(十二)——UIButton+AFNetworking
源码阅读:AFNetworking(十三)——UIImageView+AFNetworking
源码阅读:AFNetworking(十四)——UIProgressView+AFNetworking