如何使用 NSCache [英] How to use NSCache

查看:22
本文介绍了如何使用 NSCache的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以举例说明如何使用 NSCache 来缓存字符串吗?或者任何人都有一个很好的解释的链接?我似乎找不到任何..

Can someone give an example on how to use NSCache to cache a string? Or anyone has a link to a good explanation? I can't seem to find any..

推荐答案

您可以像使用 NSMutableDictionary 一样使用它.不同之处在于,当 NSCache 检测到内存压力过大(即缓存过多值)时,它会释放其中一些值以腾出空间.

You use it the same way you would use NSMutableDictionary. The difference is that when NSCache detects excessive memory pressure (i.e. it's caching too many values) it will release some of those values to make room.

如果您可以在运行时重新创建这些值(通过从 Internet 下载、进行计算等),那么 NSCache 可能会满足您的需求.如果无法重新创建数据(例如,它是用户输入、时间敏感等),则不应将其存储在 NSCache 中,因为它将在那里销毁.

If you can recreate those values at runtime (by downloading from the Internet, by doing calculations, whatever) then NSCache may suit your needs. If the data cannot be recreated (e.g. it's user input, it is time-sensitive, etc.) then you should not store it in an NSCache because it will be destroyed there.

示例,未考虑线程安全:

Example, not taking thread safety into account:

// Your cache should have a lifetime beyond the method or handful of methods
// that use it. For example, you could make it a field of your application
// delegate, or of your view controller, or something like that. Up to you.
NSCache *myCache = ...;
NSAssert(myCache != nil, @"cache object is missing");

// Try to get the existing object out of the cache, if it's there.
Widget *myWidget = [myCache objectForKey: @"Important Widget"];
if (!myWidget) {
    // It's not in the cache yet, or has been removed. We have to
    // create it. Presumably, creation is an expensive operation,
    // which is why we cache the results. If creation is cheap, we
    // probably don't need to bother caching it. That's a design
    // decision you'll have to make yourself.
    myWidget = [[[Widget alloc] initExpensively] autorelease];

    // Put it in the cache. It will stay there as long as the OS
    // has room for it. It may be removed at any time, however,
    // at which point we'll have to create it again on next use.
    [myCache setObject: myWidget forKey: @"Important Widget"];
}

// myWidget should exist now either way. Use it here.
if (myWidget) {
    [myWidget runOrWhatever];
}

这篇关于如何使用 NSCache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆