NSCache

2020-12-02  本文已影响0人  爱豆一颗心

NSCache

介绍

方法

属性

代码演练

@property (nonatomic, strong) NSCache *cache;
- (NSCache *)cache {
    if (_cache == nil) {
        _cache = [[NSCache alloc] init];
        _cache.delegate = self;
        _cache.countLimit = 10;
    }
    return _cache;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    for (int i = 0; i < 20; ++i) {
        NSString *str = [NSString stringWithFormat:@"%d", i];
        NSLog(@"set -> %@", str);
        [self.cache setObject:str forKey:@(i)];
        NSLog(@"set -> %@ over", str);
    }

    // 遍历缓存
    NSLog(@"------");

    for (int i = 0; i < 20; ++i) {
        NSLog(@"%@", [self.cache objectForKey:@(i)]);
    }
}

// 代理方法,仅供观察使用,开发时不建议重写此方法
- (void)cache:(NSCache *)cache willEvictObject:(id)obj {
    NSLog(@"remove -> %@", obj);
}

修改网络图片框架

///  图像缓冲池
@property (nonatomic, strong) NSCache *imageCache;
- (NSCache *)imageCache {
    if (_imageCache == nil) {
        _imageCache = [[NSCache alloc] init];
        _imageCache.countLimit = 15;
    }
    return _imageCache;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    for (AppInfo *app in self.appList) {
        NSLog(@"%@ %@", [[DownloadImageManager sharedManager].imageCache objectForKey:app.icon], app.name);
    }
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        // 注册通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearMemory) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    }
    return self;
}

// 提示:虽然执行不到,但是写了也无所谓
- (void)dealloc {
    // 删除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)clearMemory {
    NSLog(@"%s", __FUNCTION__);

    // 取消所有下载操作
    [self.downloadQueue cancelAllOperations];

    // 删除缓冲池
    [self.operationChache removeAllObjects];
}

注意:内存警告或者超出限制后,缓存中的任何对象,都有可能被清理。使用 NSCache 做缓存一定要保证能够有恢复的通道!

上一篇 下一篇

猜你喜欢

热点阅读