編輯:關於Android編程
本文的中文注釋代碼demo更新在我的github上。
SDWebImage是一個十分有名的Objective-C第三方開源框架,作用是:
Asynchronous image downloader with cache support as a UIImageView category
一個異步的圖片下載與緩存的UIImageViewCategory。
本文也將對SDWebImage的源代碼進行一次簡單的解析,當作學習和記錄。
SDWebImage源代碼較長,本文會分為一個一個部分進行解析。本次解析的部分就是SDImageCache。
SDImageCache使用
SDWebImage的使用十分簡單,比較常用的一個接口:
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
只需要一個url和一個placeholderimage,就可以下載圖片和設置占位圖。
整體結構
SDWebImage整體項目結構圖:
主要分為以下幾塊:
1.頭文件、宏定義、cancel接口
2.Downloader:下載圖片
3.Cache:圖片緩存
4.Utils:
SDWebImageManager:管理類
SDWebImageDecoder:圖片解壓縮類
SDWebImagePrefetcher:圖片預加載類
5.Categories:相關類使用接口
Cache
SDImageCache是用來緩存圖片到內存以及硬盤,它主要包含以下幾類方法:
* 創建Cache空間和路徑
* 存儲圖片
* 讀取圖片
* 刪除圖片
* 刪除緩存
* 清理緩存
* 獲取硬盤緩存大小
* 判斷key是否存在在硬盤
創建Cache空間和路徑
SDImageCache的初始化方法就是初始化一些基本的值和注冊相關的notification。
相關方法如下:
//單例
+ (SDImageCache *)sharedImageCache;
//初始化一個namespace空間
- (id)initWithNamespace:(NSString *)ns;
//初始化一個namespace空間和存儲的路徑
- (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory;
//存儲路徑
-(NSString *)makeDiskCachePath:(NSString*)fullNamespace;
//添加只讀cache的path
- (void)addReadOnlyCachePath:(NSString *)path;
實現如下:
//標准單例創建方法
+ (SDImageCache *)sharedImageCache {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
//添加只讀的cachePath
- (void)addReadOnlyCachePath:(NSString *)path {
//只讀路徑,只在查找圖片時候使用
if (!self.customPaths) {
self.customPaths = [NSMutableArray new];
}
if (![self.customPaths containsObject:path]) {
[self.customPaths addObject:path];
}
}
//初始化默認方法
- (id)init {
return [self initWithNamespace:@"default"];
}
- (id)initWithNamespace:(NSString *)ns {
//獲取路徑,再初始化
NSString *path = [self makeDiskCachePath:ns];
return [self initWithNamespace:ns diskCacheDirectory:path];
}
- (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory {
if ((self = [super init])) {
NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
// initialise PNG signature data
//初始化PNG圖片的標簽數據
kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8];
// Create IO serial queue
//創建 serial queue
_ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
// Init default values
//默認存儲時間一周
_maxCacheAge = kDefaultCacheMaxCacheAge;
// Init the memory cache
//初始化內存cache對象
_memCache = [[AutoPurgeCache alloc] init];
_memCache.name = fullNamespace;
// Init the disk cache
//初始化硬盤緩存路徑
if (directory != nil) {
_diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];
} else {
//默認路徑
NSString *path = [self makeDiskCachePath:ns];
_diskCachePath = path;
}
// Set decompression to YES
//需要壓縮圖片
_shouldDecompressImages = YES;
// memory cache enabled
//需要cache在內存
_shouldCacheImagesInMemory = YES;
// Disable iCloud
//禁止icloud
_shouldDisableiCloud = YES;
dispatch_sync(_ioQueue, ^{
_fileManager = [NSFileManager new];
});
#if TARGET_OS_IOS
// Subscribe to app events
//app相關warning,包括內存warning,app關閉notification,到後台notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(clearMemory)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(cleanDisk)
name:UIApplicationWillTerminateNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(backgroundCleanDisk)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
#endif
}
return self;
}
其中需要說一下的是
kPNGSignatureData,它是用來判斷是否是PNG圖片的前綴標簽數據,它的初始化數據
kPNGSignatureBytes的來源如下:
// PNG圖片的標簽值
static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
存儲圖片
存儲圖片主要分為2塊:
* 存儲到內存
直接計算圖片大小後,用NSCache *memCache存儲
* 存儲到硬盤
先將UIImage轉為NSData,然後通過NSFileManager *_fileManager創建存儲路徑文件夾和圖片存儲文件
相關方法如下:
//存儲image到key
- (void)storeImage:(UIImage *)image forKey:(NSString *)key;
//存儲image到key,是否硬盤緩存
- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;
//存儲image,是否重新計算圖片,服務器的數據來源,key,是否硬盤緩存
- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;
//硬盤緩存,key
- (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)key;
//存儲方法
- (void)storeImage:(UIImage *)image forKey:(NSString *)key {
[self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES];
}
//存儲方法
- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk {
[self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk];
}
//存儲到硬盤
- (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)key {
//沒有圖片返回
if (!imageData) {
return;
}
//判斷是否存在硬盤存儲的文件夾
if (![_fileManager fileExistsAtPath:_diskCachePath]) {
//沒有澤創建
[_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
}
// get cache Path for image key
//獲取key的完整存儲路徑
NSString *cachePathForKey = [self defaultCachePathForKey:key];
// transform to NSUrl
NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey];
//存儲圖片
[_fileManager createFileAtPath:cachePathForKey contents:imageData attributes:nil];
// disable iCloud backup
//金庸icloud
if (self.shouldDisableiCloud) {
[fileURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
}
}
//存儲圖片基礎方法
- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk {
if (!image || !key) {
return;
}
// if memory cache is enabled
//是否緩存在內存中國年
if (self.shouldCacheImagesInMemory) {
//獲取圖片大小
NSUInteger cost = SDCacheCostForImage(image);
//設置緩存
[self.memCache setObject:image forKey:key cost:cost];
}
//是否硬盤存儲
if (toDisk) {
dispatch_async(self.ioQueue, ^{
NSData *data = imageData;
if (image && (recalculate || !data)) {
#if TARGET_OS_IPHONE
// We need to determine if the image is a PNG or a JPEG
// PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html)
// The first eight bytes of a PNG file always contain the following (decimal) values:
// 137 80 78 71 13 10 26 10
// If the imageData is nil (i.e. if trying to save a UIImage directly or the image was transformed on download)
// and the image has an alpha channel, we will consider it PNG to avoid losing the transparency
int alphaInfo = CGImageGetAlphaInfo(image.CGImage);
//判斷是否有alpha
BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone ||
alphaInfo == kCGImageAlphaNoneSkipFirst ||
alphaInfo == kCGImageAlphaNoneSkipLast);
//有alpha肯定是png
BOOL imageIsPng = hasAlpha;
// But if we have an image data, we will look at the preffix
//查看圖片前幾個字節,是否是png
if ([imageData length] >= [kPNGSignatureData length]) {
imageIsPng = ImageDataHasPNGPreffix(imageData);
}
//png圖
if (imageIsPng) {
data = UIImagePNGRepresentation(image);
}
//jpeg圖
else {
data = UIImageJPEGRepresentation(image, (CGFloat)1.0);
}
#else
data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil];
#endif
}
//存儲到硬盤
[self storeImageDataToDisk:data forKey:key];
});
}
}
其中對於獲取key的完整路徑處理
NSString *cachePathForKey = [self defaultCachePathForKey:key];,還做了md5的加密,具體實現如下:
//path組合key
- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path {
NSString *filename = [self cachedFileNameForKey:key];
return [path stringByAppendingPathComponent:filename];
}
//默認路徑的keypath
- (NSString *)defaultCachePathForKey:(NSString *)key {
return [self cachePathForKey:key inPath:self.diskCachePath];
}
#pragma mark SDImageCache (private)
//MD5加密key
- (NSString *)cachedFileNameForKey:(NSString *)key {
const char *str = [key UTF8String];
if (str == NULL) {
str = "";
}
unsigned char r[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, (CC_LONG)strlen(str), r);
NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
r[11], r[12], r[13], r[14], r[15], [[key pathExtension] isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", [key pathExtension]]];
return filename;
}
讀取圖片
讀取圖片主要分為兩步:
* 內存cache讀取
直接讀取內存cacheself.memCache
* 硬盤圖片讀取
先從內存讀取cache,如果不存在,則從硬盤讀取,並且有必要的情況下存儲到內存cache中
相關方法如下:
//cache存儲位置enum
typedef NS_ENUM(NSInteger, SDImageCacheType) {
/**
* The image wasn't available the SDWebImage caches, but was downloaded from the web.
*/
SDImageCacheTypeNone,
/**
* The image was obtained from the disk cache.
*/
SDImageCacheTypeDisk,
/**
* The image was obtained from the memory cache.
*/
SDImageCacheTypeMemory
};
//3個cache block
typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType);
//異步請求緩存圖片,通過block
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;
//直接讀取cache的圖片
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;
//通過key,直接讀取硬盤
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key;
//內存直接讀取image
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key {
return [self.memCache objectForKey:key];
}
//硬盤直接讀取image
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key {
// First check the in-memory cache...
//先檢查內存中是否含有
UIImage *image = [self imageFromMemoryCacheForKey:key];
if (image) {
return image;
}
// Second check the disk cache...
//獲取硬盤存儲的image
UIImage *diskImage = [self diskImageForKey:key];
//如果獲取到了,並且需要存儲到內存cache
if (diskImage && self.shouldCacheImagesInMemory) {
//存儲到cache
NSUInteger cost = SDCacheCostForImage(diskImage);
[self.memCache setObject:diskImage forKey:key cost:cost];
}
return diskImage;
}
//異步獲取圖片
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock {
if (!doneBlock) {
return nil;
}
//沒有key,則返回不存在
if (!key) {
doneBlock(nil, SDImageCacheTypeNone);
return nil;
}
// First check the in-memory cache...
//先獲取memory中的圖片
UIImage *image = [self imageFromMemoryCacheForKey:key];
if (image) {
doneBlock(image, SDImageCacheTypeMemory);
return nil;
}
NSOperation *operation = [NSOperation new];
//硬盤查找速度較慢,在子線程中查找
dispatch_async(self.ioQueue, ^{
if (operation.isCancelled) {
return;
}
//創建autoreleasepool
@autoreleasepool {
//獲取硬盤圖片
UIImage *diskImage = [self diskImageForKey:key];
//如果獲取到了,並且需要存儲到內存cache
if (diskImage && self.shouldCacheImagesInMemory) {
//獲得大小並存儲圖片
NSUInteger cost = SDCacheCostForImage(diskImage);
[self.memCache setObject:diskImage forKey:key cost:cost];
}
//回到主線程返回結果
dispatch_async(dispatch_get_main_queue(), ^{
doneBlock(diskImage, SDImageCacheTypeDisk);
});
}
});
return operation;
}
其中,對於從硬盤存儲獲取圖片
UIImage *diskImage = [self diskImageForKey:key];的實現如下:
//硬盤返回圖片
- (UIImage *)diskImageForKey:(NSString *)key {
//搜索所有的path,然後把這個key的圖片拿出來
NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
//如果有data
if (data) {
//data轉為image,實現在UIImage+MultiFormat中
UIImage *image = [UIImage sd_imageWithData:data];
//圖片適配屏幕
image = [self scaledImageForKey:key image:image];
//壓縮圖片,實現在SDWebImageDecoder
if (self.shouldDecompressImages) {
image = [UIImage decodedImageWithImage:image];
}
return image;
}
else {
return nil;
}
}
//適配屏幕
- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
//方法在SDWebImageCompat中
return SDScaledImageForKey(key, image);
}
//從所有path中讀取圖片
- (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key {
//默認讀取路徑
NSString *defaultPath = [self defaultCachePathForKey:key];
NSData *data = [NSData dataWithContentsOfFile:defaultPath];
//讀取到則返回
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
//去掉path extension,這塊應該是為了兼容某一個版本添加的path extension,所以本質上是個兼容舊版本的邏輯判斷
data = [NSData dataWithContentsOfFile:[defaultPath stringByDeletingPathExtension]];
if (data) {
return data;
}
//本地只讀路徑讀取
NSArray *customPaths = [self.customPaths copy];
for (NSString *path in customPaths) {
//獲取只讀路徑中的filepath
NSString *filePath = [self cachePathForKey:key inPath:path];
NSData *imageData = [NSData dataWithContentsOfFile:filePath];
if (imageData) {
return imageData;
}
// 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
//同上
imageData = [NSData dataWithContentsOfFile:[filePath stringByDeletingPathExtension]];
if (imageData) {
return imageData;
}
}
return nil;
}
這邊牽扯到好幾個其他類的方法,這邊就不先標注它們的源代碼了,等到講到的時候再講一下。
刪除圖片
刪除圖片方法分為兩步:
* 先從cache刪除緩存圖片
* 然後硬盤刪除對應文件
相關方法如下:
//通過key,刪除圖片
- (void)removeImageForKey:(NSString *)key;
//異步刪除圖片,調用完成block
- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion;
//刪除圖片,同時從硬盤刪除
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;
//異步刪除,同時刪除硬盤
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion;
//刪除圖片
- (void)removeImageForKey:(NSString *)key {
[self removeImageForKey:key withCompletion:nil];
}
//刪除圖片
- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion {
[self removeImageForKey:key fromDisk:YES withCompletion:completion];
}
//刪除圖片
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk {
[self removeImageForKey:key fromDisk:fromDisk withCompletion:nil];
}
//刪除圖片基礎方法
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion {
//不存在key返回
if (key == nil) {
return;
}
//需要用memory,先從cache刪除圖片
if (self.shouldCacheImagesInMemory) {
[self.memCache removeObjectForKey:key];
}
//硬盤刪除
if (fromDisk) {
dispatch_async(self.ioQueue, ^{
//直接刪除路徑下key對應的文件名字
[_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
}
});
} else if (completion){
completion();
}
}
刪除緩存
刪除緩存也分為兩塊:
* 直接清空緩存memCache
* 刪除硬盤存儲目錄,再重新創建目錄
相關方法
//刪除緩存圖片
- (void)clearMemory;
//刪除硬盤存儲圖片,調用完成block
- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion;
//刪除硬盤存儲圖片
- (void)clearDisk;
//輕松memcache
- (void)clearMemory {
[self.memCache removeAllObjects];
}
//刪除硬盤存儲
- (void)clearDisk {
[self clearDiskOnCompletion:nil];
}
//刪除硬盤存儲基礎方法
- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion
{
dispatch_async(self.ioQueue, ^{
//直接刪除存文件的路徑
[_fileManager removeItemAtPath:self.diskCachePath error:nil];
//重新創建文件路徑
[_fileManager createDirectoryAtPath:self.diskCachePath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
}
});
}
清理緩存
清理緩存的目標是將過期的圖片和確保硬盤存儲大小小於最大存儲許可。
清理緩存的方法也是分為兩步:
* 清除所有過期圖片
* 在硬盤存儲大小大於最大存儲許可大小時,將舊圖片進行刪除,刪除到一半最大許可以下
相關方法:
//清理硬盤緩存圖片
- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock;
//清理硬盤緩存圖片
- (void)cleanDisk;
//清理硬盤
- (void)cleanDisk {
[self cleanDiskWithCompletionBlock:nil];
}
//清理硬盤基礎方法
//清理硬盤的目的是為了緩解硬盤壓力,以及過期圖片,超大小圖片等
- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock {
dispatch_async(self.ioQueue, ^{
//硬盤存儲路徑獲取
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
//是否是目錄,獲取修改日期,獲取size大小
NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];
// This enumerator prefetches useful properties for our cache files.
//迭代器遍歷
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
includingPropertiesForKeys:resourceKeys
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:NULL];
//獲取應該過期的日期
NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge];
//緩存路徑與3個key值
NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary];
//獲取總的目錄下文件大小
NSUInteger currentCacheSize = 0;
// Enumerate all of the files in the cache directory. This loop has two purposes:
//
// 1. Removing files that are older than the expiration date.
// 2. Storing file attributes for the size-based cleanup pass.
//需要刪除的路徑存儲
NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init];
//遍歷路徑下的所有文件於文件夾
for (NSURL *fileURL in fileEnumerator) {
//獲取該文件路徑的3種值
NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL];
// Skip directories.
//跳過目錄
if ([resourceValues[NSURLIsDirectoryKey] boolValue]) {
continue;
}
// Remove files that are older than the expiration date;
//獲取修改日期
NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
//在有效期日期之前的文件需要刪除,添加到
if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
[urlsToDelete addObject:fileURL];
continue;
}
// Store a reference to this file and account for its total size.
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
//獲取文件大小
currentCacheSize += [totalAllocatedSize unsignedIntegerValue];
//存儲值
[cacheFiles setObject:resourceValues forKey:fileURL];
}
//刪除所有的過期圖片
for (NSURL *fileURL in urlsToDelete) {
[_fileManager removeItemAtURL:fileURL error:nil];
}
// 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.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) {
// Target half of our maximum cache size for this cleanup pass.
//目標空間
const NSUInteger desiredCacheSize = self.maxCacheSize / 2;
// Sort the remaining cache files by their last modification time (oldest first).
//排序所有filepath,時間排序
NSArray *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 ([_fileManager removeItemAtURL:fileURL error:nil]) {
NSDictionary *resourceValues = cacheFiles[fileURL];
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
currentCacheSize -= [totalAllocatedSize unsignedIntegerValue];
if (currentCacheSize < desiredCacheSize) {
break;
}
}
}
}
//回調block
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock();
});
}
});
}
這邊需要提一下,當app進入後台,發送notification,調用的方法,就是清理硬盤內存,方法如下:
//後台清理硬盤
- (void)backgroundCleanDisk {
Class UIApplicationClass = NSClassFromString(@"UIApplication");
if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
return;
}
UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
//設置後台存活,在ios7以上最多存在3分鐘,7以下是10分鐘
__block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
//在存活期間清理硬盤
// Start the long-running task and return immediately.
[self cleanDiskWithCompletionBlock:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
獲取硬盤緩存大小
獲取硬盤緩存大小直接讀取硬盤路徑下的文件數量和每個文件大小,進行累加。
相關方法如下:
typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize);
//獲得硬盤存儲空間大小
- (NSUInteger)getSize;
//獲得硬盤空間圖片數量
- (NSUInteger)getDiskCount;
//異步計算硬盤空間大小
- (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock;
//獲取硬盤存儲的大小
- (NSUInteger)getSize {
__block NSUInteger size = 0;
dispatch_sync(self.ioQueue, ^{
//硬盤路徑迭代器
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
for (NSString *fileName in fileEnumerator) {
//拼接路徑
NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
//獲取路徑下的文件與文件夾屬性
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
//算大小
size += [attrs fileSize];
}
});
return size;
}
//獲取硬盤存儲的數量
- (NSUInteger)getDiskCount {
__block NSUInteger count = 0;
dispatch_sync(self.ioQueue, ^{
//硬盤路徑迭代器
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
count = [[fileEnumerator allObjects] count];
});
return count;
}
//異步獲取硬盤緩存大小
- (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock {
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
dispatch_async(self.ioQueue, ^{
NSUInteger fileCount = 0;
NSUInteger totalSize = 0;
//迭代所有路徑下文件
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
includingPropertiesForKeys:@[NSFileSize]
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:NULL];
//遍歷文件和文件夾
for (NSURL *fileURL in fileEnumerator) {
NSNumber *fileSize;
//獲取size
[fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
totalSize += [fileSize unsignedIntegerValue];
fileCount += 1;
}
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(fileCount, totalSize);
});
}
});
}
判斷key是否存在在硬盤
判斷key是否存在在硬盤中,直接從硬盤中判斷是否存在此key的文件路徑
相關方法如下:
typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache);
//異步判斷是否存在key的圖片
- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
//同步判斷是否存在key的圖片
- (BOOL)diskImageExistsWithKey:(NSString *)key;
//直接讀取
- (BOOL)diskImageExistsWithKey:(NSString *)key {
BOOL exists = NO;
// this is an exception to access the filemanager on another queue than ioQueue, but we are using the shared instance
// from apple docs on NSFileManager: The methods of the shared NSFileManager object can be called from multiple threads safely.
exists = [[NSFileManager defaultManager] fileExistsAtPath:[self defaultCachePathForKey:key]];
// 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
if (!exists) {
exists = [[NSFileManager defaultManager] fileExistsAtPath:[[self defaultCachePathForKey:key] stringByDeletingPathExtension]];
}
return exists;
}
//判斷是否有key的文件
- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
dispatch_async(_ioQueue, ^{
//直接去讀默認文件
BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]];
// 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
//不存在去讀區去掉path extension的方式
if (!exists) {
exists = [_fileManager fileExistsAtPath:[[self defaultCachePathForKey:key] stringByDeletingPathExtension]];
}
//回調block
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(exists);
});
}
});
}
總結
SDWebImage本身牽扯到很多內容,這篇文章先整體講了一下SDImageCache的設計與實現,它有如下優點:
* 1.memory的cache和硬盤存儲結合存儲
* 2.後台清理硬盤存儲空間
* 3.NSURL的文件讀取用途和相關文件夾迭代器和獲取
* 4.精妙的kPNGSignatureData判斷是否是PNG圖片
* 5.分別提供同步和異步的方法
當然也有一個path extension文件名問題。
這也告訴我們一個道理,很多時候文件名一定要想好怎麼去存儲,一旦進行修改了,後續兼容會很麻煩。
Android生命周期估計連初學者都再熟悉不過的東西了,但這裡我拋出幾個問題,或許大家以前沒有想過或者可能認識的有些錯誤。 一、當A啟動B時,A和B生命周期方法執行的先後
我們做一些好友列表或者商品列表的時候,居多的需求可能就是需要列表拖拽了,而我們選擇了ListView,也是因為使用ListView太久遠了,導致對他已經有濃厚的感情了
廢話不多說,先看效果圖: package com.example.circlemenuofbottom.anim;import android.v
微信與飛信兩者都是以消耗流量來進行的,現如今微信的功能越來越強大,用戶也很多,沒有太大的約束。飛信的話,現在用戶相對少些,有一定的局限性。個人認為微信來的更