用于存储UIImage ios的NSCache初始化

我正在使用NSCache来存储图像。 但是这里的问题是一旦我在控制器之间切换,NSCache清空。 我希望项目在那里至less在应用程序closures或用户注销。 比方说,我有一个选项卡视图,我从第一个选项卡中的数据存储的图像。 当我转到第二个选项卡并切换回第一个时,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. 如果应用程序在后台进行NSCache将清理。

  2. 你总是创build一个新的caching,更好的办法是使用sharedInstance只有一个NSCache对象。