gpt4 book ai didi

ios - NSCache初始化存储UIImage ios

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:57:51 28 4
gpt4 key购买 nike

我正在使用 NSCache 来存储图像。但是这里的问题是一旦我在 Controller 之间切换,NSCache 就会清空。我希望这些项目至少在应用程序关闭或用户注销之前一直存在。可以说我有一个选项卡 View ,我正在将数据中的图像存储在第一个选项卡中。当我转到第二个选项卡并切换回第一个选项卡时,NSCache 再次初始化。

这是我的代码:-

- (void)viewDidLoad {
[super viewDidLoad];
if(imageCache==nil)
{
imageCache=[[NSCache alloc]init];
NSLog(@"initialising");
}
[imageCache setEvictsObjectsWithDiscardedContent:NO];
}


(void) reloadMessages {

[Data getClassMessagesWithClassCode:_classObject.code successBlock:^(id object) {
NSMutableArray *messagesArr = [[NSMutableArray alloc] init];
for (PFObject *groupObject in object) {

PFFile *file=[groupObject objectForKey:@"attachment"];
NSString *url1=file.url;
NSLog(@"%@ is url to the image",url1);
UIImage *image = [imageCache objectForKey:url1];
if(image)
{
NSLog(@"This is cached");

}
else{

NSURL *imageURL = [NSURL URLWithString:url1];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:imageURL]];

if(image)
{
NSLog(@"Caching ....");
[imageCache setObject:image forKey:url1];
}

}

}

控件永远不会转到第一个 if 语句。我错过了什么吗?

最佳答案

@interface Sample : NSObject

+ (Sample*)sharedInstance;

// set
- (void)cacheImage:(UIImage*)image forKey:(NSString*)key;
// get
- (UIImage*)getCachedImageForKey:(NSString*)key;

@end

#import "Sample.h"

static Sample *sharedInstance;

@interface Sample ()
@property (nonatomic, strong) NSCache *imageCache;
@end

@implementation Sample

+ (Sample*)sharedInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[Sample alloc] init];
});
return sharedInstance;
}
- (instancetype)init {
self = [super init];
if (self) {
self.imageCache = [[NSCache alloc] init];
}
return self;
}

- (void)cacheImage:(UIImage*)image forKey:(NSString*)key {
[self.imageCache setObject:image forKey:key];
}

- (UIImage*)getCachedImageForKey:(NSString*)key {
return [self.imageCache objectForKey:key];
}

在您的代码中:

UIImage *image = [[Sample sharedInstance] getCachedImageForKey:url1];
if(image)
{
NSLog(@"This is cached");

}
else{

NSURL *imageURL = [NSURL URLWithString:url1];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:imageURL]];

if(image)
{
NSLog(@"Caching ....");
[[Sample sharedInstance] cacheImage:image forKey:url1];
}

}
  1. 如果 App 进入后台,NSCache 将进行清理。

  2. 您总是会创建一个新的缓存,更好的方法是将 sharedInstance 与一个 NSCache 对象一起使用。

关于ios - NSCache初始化存储UIImage ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28366397/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com