用于存储UIImage ios的NSCache初始化

use*_*823 2 objective-c uiimage ios nscache

我正在使用NSCache来存储图像.但问题是,一旦我在控制器之间切换,NSCache会清空.我希望项目至少存在,直到应用程序关闭或用户注销.假设我有一个标签视图,我在第一个标签中存储数据中的图像.当我转到第二个选项卡并切换回第一个选项卡时,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];
            }

        }

    }
Run Code Online (Sandbox Code Playgroud)

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

iOS*_*eer 9

@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];
}
Run Code Online (Sandbox Code Playgroud)

在你的代码中:

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];
        }

    }
Run Code Online (Sandbox Code Playgroud)
  1. 如果App进入后台NSCache将清除.

  2. 您总是创建一个新的缓存,更好的方法是使用sharedInstance只有一个NSCache对象.