[英]Cache Processed (e.g. blurred or edited) Images
Is there a best practice or library that helps cache processed images (ie images that have been created while the app is running) in iOS? 是否有最佳实践或库可帮助在iOS中缓存已处理的图像(即在应用运行时创建的图像)? I use SDWebImage for images that I download, but in various places in the app I blur or in other ways process some of these images. 我将SDWebImage用于下载的图像,但是在应用程序的各个位置,我模糊或以其他方式处理其中的一些图像。 I would like to store the processed images in a cache so that I can access them easily rather than reprocess each time a user opens that image. 我想将处理后的图像存储在缓存中,以便可以轻松访问它们,而不是每次用户打开该图像时都进行重新处理。 What's the best way to do this? 最好的方法是什么?
Thanks! 谢谢!
The answer it seems is using NSCache. 答案似乎是使用NSCache。 It's quite straightforward to do. 这很容易做到。 I ended up with a subclass of NSCache to make sure memory warnings are handled. 我最终得到了NSCache的子类,以确保处理了内存警告。
Implementation of NATAutoPurgeCache (heavily based on other posts on StackOverflow) 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
And using it when needed for an image: (in this case to store a blurred image) 并在需要图像时使用它:(在这种情况下,用于存储模糊的图像)
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.