diff --git a/SDWebImage/Core/SDImageCache.m b/SDWebImage/Core/SDImageCache.m index e9f1d584..c1f99a89 100644 --- a/SDWebImage/Core/SDImageCache.m +++ b/SDWebImage/Core/SDImageCache.m @@ -672,7 +672,14 @@ static NSString * _defaultDiskCacheDirectory; #if SD_UIKIT || SD_MAC - (void)applicationWillTerminate:(NSNotification *)notification { - [self deleteOldFilesWithCompletionBlock:nil]; + // On iOS/macOS, the async opeartion to remove exipred data will be terminated quickly + // Try using the sync operation to ensure we reomve the exipred data + if (!self.config.shouldRemoveExpiredDataWhenTerminate) { + return; + } + dispatch_sync(self.ioQueue, ^{ + [self.diskCache removeExpiredData]; + }); } #endif diff --git a/SDWebImage/Core/SDImageCacheConfig.h b/SDWebImage/Core/SDImageCacheConfig.h index 4d6e79b0..f2d19203 100644 --- a/SDWebImage/Core/SDImageCacheConfig.h +++ b/SDWebImage/Core/SDImageCacheConfig.h @@ -67,6 +67,12 @@ typedef NS_ENUM(NSUInteger, SDImageCacheConfigExpireType) { */ @property (assign, nonatomic) BOOL shouldRemoveExpiredDataWhenEnterBackground; +/** + * Whether or not to remove the expired disk data when application been terminated. This operation is processed in sync to ensure clean up. + * Defaults to YES. + */ +@property (assign, nonatomic) BOOL shouldRemoveExpiredDataWhenTerminate; + /** * The reading options while reading cache from disk. * Defaults to 0. You can set this to `NSDataReadingMappedIfSafe` to improve performance. diff --git a/SDWebImage/Core/SDImageCacheConfig.m b/SDWebImage/Core/SDImageCacheConfig.m index 40a53348..ad5bcaad 100644 --- a/SDWebImage/Core/SDImageCacheConfig.m +++ b/SDWebImage/Core/SDImageCacheConfig.m @@ -29,6 +29,7 @@ static const NSInteger kDefaultCacheMaxDiskAge = 60 * 60 * 24 * 7; // 1 week _shouldCacheImagesInMemory = YES; _shouldUseWeakMemoryCache = YES; _shouldRemoveExpiredDataWhenEnterBackground = YES; + _shouldRemoveExpiredDataWhenTerminate = YES; _diskCacheReadingOptions = 0; _diskCacheWritingOptions = NSDataWritingAtomic; _maxDiskAge = kDefaultCacheMaxDiskAge; @@ -46,6 +47,7 @@ static const NSInteger kDefaultCacheMaxDiskAge = 60 * 60 * 24 * 7; // 1 week config.shouldCacheImagesInMemory = self.shouldCacheImagesInMemory; config.shouldUseWeakMemoryCache = self.shouldUseWeakMemoryCache; config.shouldRemoveExpiredDataWhenEnterBackground = self.shouldRemoveExpiredDataWhenEnterBackground; + config.shouldRemoveExpiredDataWhenTerminate = self.shouldRemoveExpiredDataWhenTerminate; config.diskCacheReadingOptions = self.diskCacheReadingOptions; config.diskCacheWritingOptions = self.diskCacheWritingOptions; config.maxDiskAge = self.maxDiskAge;