问题
I am using NSCache to store images. But problem here is once I switch between controllers , NSCache empties. I want the items to be there atleast until application is closed or user logs out . Lets say I have a tab view and I am storing images from the data in 1st tab . When I go to second tab and switch back to first ,NSCache is initialized again.
Here is my code :-
- (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];
}
}
}
The control never goes to the first if statement. Am I missing something?
回答1:
@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];
}
In your code:
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];
}
}
If App goes in background NSCache will cleans.
You always create a new cache, better way is use sharedInstance with only one NSCache object.
来源:https://stackoverflow.com/questions/28366397/nscache-initialization-for-storing-uiimage-ios