Effective Objective-C 2.0:Item 50: Use NSCache Instead of NSDictionary for Caches

本文介绍了在Objective-C中,为何使用NSCache而非NSDictionary作为缓存的最佳实践。NSCache在系统内存不足时会自动清理,并按使用频率优先删除,避免了手动编写内存管理代码。此外,NSCache线程安全,不复制键且支持设置对象数量和总成本限制。通过设置这些限制,可以更好地控制缓存行为。使用NSPurgeableData结合NSCache,还可以实现数据的自动释放功能,提高应用程序响应速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Item 50: Use NSCache Instead of NSDictionary for Caches

A common problem encountered when developing a Mac OS X or an iOS application that downloads images from the Internet is deciding what to do about caching them. A good first approach is to use a dictionary to store in memory images that have been downloaded, such that they don’t need to be downloaded again if they are requested later. A naïve developer will simply use an NSDictionary (or rather a mutable one) because that’s a commonly used class. However, an even better class, called NSCache, is also part of the Foundation framework and has been designed exactly for this task.

The benefit of NSCache over an NSDictionary is that as system memory becomes full, the cache is automatically pruned. When using a dictionary, you often end up having to write pruning code yourself by hooking into system notifications for low memory. However, NSCache offers this automatically; because it is part of the Foundation framework, it will be able to hook in deeper to the system than you could yourself. An NSCachewill also prune the least recently used objects first. Writing the code to support this yourself with a dictionary would be quite complex.

Also, an NSCache does not copy keys but rather retains them. This is something that can be controlled on NSDictionary but requires more complex code (see Item 49). A cache usually would rather not copy the keys because often, the key will be an object that does not support copying. Since NSCache doesn’t copy by default, it makes it an easier class to work with in these situations. Also, NSCache is thread safe. This is certainly not true of an NSDictionary, which means that you can poke away at an NSCache from multiple threads at the same time without having to introduce any locks of your own. This is usually useful for a cache because you may want to read from it in one thread, and, if a certain key doesn’t exist, you may download the data for that key. The callbacks for downloading may be in a background thread, so you end up adding to the cache in this other thread.

You can control when a cache will prune its contents. Two

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值