是否有最佳实践或库可帮助缓存已处理的图像(即在应用程序运行时创建的图像)?我将SDWebImage用于我下载的图像,但在应用程序的各个地方我模糊或以其他方式处理这些图像。我想将处理后的图像存储在缓存中,以便我可以轻松访问它们,而不是每次用户打开该图像时重新处理它们。最好的方法是什么?
谢谢!
答案 0 :(得分:0)
似乎是使用NSCache的答案。这很简单。我最终得到了一个NSCache的子类,以确保处理内存警告。
NATAutoPurgeCache的实现(很大程度上基于StackOverflow上的其他帖子)
@implementation NATAutoPurgeCache
+ (NATAutoPurgeCache *)sharedCache
{
static NATAutoPurgeCache *_sharedCache = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedCache = [[self alloc] init];
});
return _sharedCache;
}
- (id)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
@end
在图像需要时使用它:(在这种情况下用于存储模糊图像)
UIImage* blurImage = [myCache objectForKey:@"blurred placeholder image"];
if (!blurImage)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
UIImage* blurImage = self.activityPic.image;
blurImage= [blurImage applyLightEffect];
dispatch_async(dispatch_get_main_queue(), ^{
self.activityPic.image = blurImage;
});
[myCache setObject:blurImage forKey:@"blurred placeholder image"];
});
}
else {
self.activityPic.image = blurImage;
}