NSCache和NSDictionary

1 NSCache和NSMutableDictionary的相同点与区别:

相同点:

NSCache和NSMutableDictionary功能用法基本是相同的。

区别:

NSCache是线程安全的,NSMutableDictionary线程不安全
NSCache线程是安全的,Mutable开发的类一般都是线程不安全的
当内存不足时NSCache会自动释放内存(所以从缓存中取数据的时候总要判断是否为空)
NSCache可以指定缓存的限额,当缓存超出限额自动释放内存

缓存限额:

缓存数量
@property NSUInteger countLimit;

缓存成本
@property NSUInteger totalCostLimit;

苹果给NSCache封装了更多的方法和属性,比NSMutableDictionary的功能要强大很多

#import "ViewController.h"

@interface ViewController () <NSCacheDelegate>

@property (nonatomic, strong) NSCache *cache;

@end

@implementation ViewController

- (NSCache *)cache {
    if (_cache == nil) {
        _cache = [[NSCache alloc] init];
        // 缓存中总共可以存储多少条
        _cache.countLimit = 5;
        // 缓存的数据总量为多少
        _cache.totalCostLimit = 1024 * 5;
        //设置NSCache的代理
        _cache.delegate = self;
    }
    return _cache;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //添加缓存数据
    for (int i = 0; i < 10; i++) {
        [self.cache setObject:[NSString stringWithFormat:@"hello %d",i] forKey:[NSString stringWithFormat:@"h%d",i]];
        NSLog(@"添加 %@",[NSString stringWithFormat:@"hello %d",i]);
    }
    
    //输出缓存中的数据
    for (int i = 0; i < 10; i++) {
        NSLog(@"%@",[self.cache objectForKey:[NSString stringWithFormat:@"h%d",i]]);
    }
    
}

//将要从NSCache中移除一项的时候执行
- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
    NSLog(@"从缓存中移除  %@",obj);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    //当收到内存警告,调用removeAllObjects 之后,无法再次往缓存中添加数据
    [self.cache removeAllObjects];
    //输出缓存中的数据
    for (int i = 0; i < 10; i++) {
        NSLog(@"%@",[self.cache objectForKey:[NSString stringWithFormat:@"h%d",i]]);
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.cache removeAllObjects];
    
    //添加缓存数据
    for (int i = 0; i < 10; i++) {
        [self.cache setObject:[NSString stringWithFormat:@"hello %d",i] forKey:[NSString stringWithFormat:@"h%d",i]];
        NSLog(@"添加 %@",[NSString stringWithFormat:@"hello %d",i]);
    }
    
    //输出缓存中的数据
    for (int i = 0; i < 10; i++) {
        NSLog(@"%@",[self.cache objectForKey:[NSString stringWithFormat:@"h%d",i]]);
    }
    
}

@end

复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享