自定义一个简单的iOS图片缓存类

时间:2024-03-06 12:11:49

#import "ImageCaChe.h"

@interface ImageCaChe ()

@property(nonatomic,strong)NSCache *memoryCache;

@end

@implementation ImageCaChe

+(instancetype)sharedCaChe{

    static ImageCaChe *sharedInstanceCache = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedInstanceCache = [[self alloc]init];

    });

    return  sharedInstanceCache;

}

-(void)loadImageWithURL:(NSURL *)url completion:(void (^)(UIImage * _Nonnull))completion{

    UIImage *cacheImage = [self getCacheImageWithURL:url];

    if(cacheImage){

        completion(cacheImage);

        return;

    }

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSData *imageData = [NSData dataWithContentsOfURL:url];

        UIImage *image = [UIImage imageWithData:imageData];

        if(image){

            [self cacheImage:image withURL:url];

        }

        dispatch_async(dispatch_get_main_queue(), ^{

            completion(image);

        });

    });

    

}

-(UIImage*)getCacheImageWithURL:(NSURL*)url{

    NSString *key = url.absoluteString;

    return [[self memoryCache]objectForKey:key];

}

-(void)cacheImage:(UIImage*)image withURL:(NSURL*)url{

    NSString *key = url.absoluteString;

    [[self memoryCache]setObject:image forKey:url];

}

-(NSCache *)memoryCache{

    static NSCache *cache = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        cache = [[NSCache alloc]init];

        cache.totalCostLimit = 50;

    });

    return cache;

}

@end