应用场景:

代码

#import <UIKit/UIKit.h>

@interface UIImage (NTESColor)

+ (UIImage *)imageWithColor:(UIColor *)color;

@end
#import <sys/stat.h>
#import "UIImage+NTESColor.h"

@interface UIColorCache : NSObject
@property (nonatomic,strong)    NSCache *colorImageCache;
@end

@implementation UIColorCache
+ (instancetype)sharedCache{
    static UIColorCache *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[UIColorCache alloc] init];
    });
    return instance;
}

- (instancetype)init{
    if (self = [super init]){
        _colorImageCache = [[NSCache alloc] init];
    }
    return self;
}

- (UIImage *)image:(UIColor *)color{
    return color ? [_colorImageCache objectForKey:[color description]] : nil;
}

- (void)setImage:(UIImage *)image
        forColor:(UIColor *)color{
    [_colorImageCache setObject:image
                         forKey:[color description]];
}
@end

@implementation UIImage (NTESColor)

+ (UIImage *)clearColorImage {
    return [UIImage imageNamed:@"Clear_color_image"];
}

+ (UIImage *)imageWithColor:(UIColor *)color {    
    if (color == nil) {
        assert(0);
        return nil;
    }
    UIImage *image = [[UIColorCache sharedCache] image:color];
    if (image == nil){
        CGFloat alphaChannel;
        [color getRed:NULL green:NULL blue:NULL alpha:&alphaChannel];
        BOOL opaqueImage = (alphaChannel == 1.0);
        CGRect rect = CGRectMake(0, 0, 1, 1);
        UIGraphicsBeginImageContextWithOptions(rect.size, opaqueImage, [UIScreen mainScreen].scale);
        [color setFill];
        UIRectFill(rect);
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [[UIColorCache sharedCache] setImage:image
                                    forColor:color];
    }
    return image;
}
@end

代码分析:

NSCache简单说明

问题一:App重启后,NSCache中的东西还存在吗? 不会

问题二:可以统计出NSCache中已经缓存的数据大小吗? 不

NSCache奇葩之处三:释放内存时,并不确定释放的对象的顺序

使用NSCache实战-给UIView类型添加圆角

iOS开发基础 - 被忽视和误解的NSCache

iOS之NSCache的简单介绍