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

查看:117
本文介绍了如何使用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.

如果你可以在运行时重新创建这些值(通过从互联网下载,通过计算,任何),然后 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天全站免登陆