用于存储 UIImage 的 NSCache 初始化 ios

NSCache initialization for storing UIImage ios

我正在使用 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];
            }

        }

    }

控件永远不会转到第一个 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. 你总是创建一个新的缓存,更好的方法是使用只有一个 NSCache 对象的 sharedInstance。