博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS. NSCache的缓存
阅读量:4290 次
发布时间:2019-05-27

本文共 1040 字,大约阅读时间需要 3 分钟。

NSCache苹果提供的一套缓存机制。 

和NSMutableDictionary使用起来相似。 

线程安全,Mutable开发的类一般都是线程不安全的。 

当内存不足时会自动释放内存(所以从缓存中取数据的时候总要判断是否为空) 。

指定缓存的限额,当缓存超出限额自动释放内存。

- (NSCache *)cache

{

    if (_cache ==nil) {

        _cache = [[NSCachealloc] init];

        

        _cache.delegate =self;

        

        // 设置缓存的个数(限额)

        _cache.countLimit =5;

//设置缓存成本(多少M)

        _cache.totalCostlimit=10M;

    }

    return _cache;

}

/// NSCache的代理方法,在对象将要从cache中移除的时候调用的

- (void)cache:(NSCache *)cache willEvictObject:(id)obj

{

    NSLog(@"移除 %@",obj);

}

    // 循环的向cache中添加对象

    for (int i =0; i < 10; i++) {

        NSString *str = [NSStringstringWithFormat:@"hello_%d",i+1];

        NSLog(@"添加 %@",str);

        NSString *key = [NSStringstringWithFormat:@"key_%d",i];

        

        [self.cachesetObject:str forKey:key];

    }

    

    // 循环的取值

    for (int i =0; i < 10; i++) {

        NSString *key = [NSStringstringWithFormat:@"key_%d",i];

        NSString *str = [self.cacheobjectForKey:key];

        NSLog(@"获取 %@",str);

    }

//清空缓存

[self.cacheremoveAllObjects];

- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    

    // 注意 : 一旦在 didReceiveMemoryWarning调用移除全部对象的方法之后,那么这个cache永远不会再去添加对象

    [self.cacheremoveAllObjects];

}

转载地址:http://uelgi.baihongyu.com/

你可能感兴趣的文章
c++ 加载so动态库中的资源
查看>>
加解密 签名
查看>>
linux top 命令分析
查看>>
Linux vmstat命令详解
查看>>
linux pmap命令
查看>>
MySQL数据同步【双主热备】
查看>>
Mysql主从复制实践手册
查看>>
nginx配置正向代理支持HTTPS
查看>>
Perf -- Linux下的系统性能调优神器
查看>>
C++ 用libcurl库进行http通讯网络编程
查看>>
秒杀多线程第十篇 生产者消费者问题
查看>>
信号量与互斥锁
查看>>
linux 查看CPU个数,核数
查看>>
string 序列化
查看>>
va_start(),va_end()函数应用
查看>>
crontab命令
查看>>
State Threads——异步回调的线性实现
查看>>
va_start va_end
查看>>
共享内存,共享缓冲区 一对多
查看>>
无锁队列的实现
查看>>