ios 如何使用 NSCache

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5755902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:40:59  来源:igfitidea点击:

How to use NSCache

iosobjective-cxcodecocoanscache

提问by Thizzer

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

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

回答by Jonathan Grynspan

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

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

If you can recreate those values at runtime (by downloading from the Internet, by doing calculations, whatever) then NSCachemay 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 NSCachebecause it will be destroyed there.

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

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];
}

回答by Gabriel.Massana

@implementation ViewController
{    
    NSCache *imagesCache;    
}


- (void)viewDidLoad
{    
    imagesCache = [[NSCache alloc] init];
}


// How to save and retrieve NSData into NSCache
NSData *imageData = [imagesCache objectForKey:@"KEY"];
[imagesCache setObject:imageData forKey:@"KEY"];

回答by PointZeroTwo

Sample code for caching a string using NSCache in Swift:

在 Swift 中使用 NSCache 缓存字符串的示例代码:

var cache = NSCache()
cache.setObject("String for key 1", forKey: "Key1")
var result = cache.objectForKey("Key1") as String
println(result) // Prints "String for key 1"

To create a single app-wide instance of NSCache (a singleton), you can easily extend NSCache to add a sharedInstance property. Just put the following code in a file called something like NSCache+Singleton.swift:

要创建 NSCache 的单个应用程序范围实例(单例),您可以轻松扩展 NSCache 以添加 sharedInstance 属性。只需将以下代码放在一个名为 NSCache+Singleton.swift 的文件中:

import Foundation

extension NSCache {
    class var sharedInstance : NSCache {
        struct Static {
            static let instance : NSCache = NSCache()
        }
        return Static.instance
    }
}

You can then use the cache anywhere in the app:

然后,您可以在应用程序的任何位置使用缓存:

NSCache.sharedInstance.setObject("String for key 2", forKey: "Key2")
var result2 = NSCache.sharedInstance.objectForKey("Key2") as String
println(result2) // Prints "String for key 2"

回答by Ajumal

sample ProjectAdd CacheController.h and .m file from the sample project to your project. In class where you want to cache data , put the below code.

示例项目示例项目中的CacheController.h 和 .m 文件添加到您的项目中。在要缓存数据的类中,放置以下代码。

[[CacheController storeInstance] setCache:@"object" forKey:@"objectforkey" ];

you can set any object using this

您可以使用此设置任何对象

[[CacheController storeInstance] getCacheForKey:@"objectforkey" ];

to retrive

检索

Important: The NSCache class incorporates various auto-removal policies. if you want cache the data for permanent or you want to remove cached data in a specific time see this answer.

重要提示:NSCache 类包含各种自动删除策略。如果您想永久缓存数据,或者您想在特定时间删除缓存的数据, 请参阅此答案

回答by Phoenix

Shouldn't the cached objects implement the NSDiscardableContent protocol?

缓存的对象不应该实现 NSDiscardableContent 协议吗?

From the NSCache class reference: A common data type stored in NSCache objects is an object that implements the NSDiscardableContent protocol. Storing this type of object in a cache has benefits, because its content can be discarded when it is not needed anymore, thus saving memory. By default, NSDiscardableContent objects in the cache are automatically removed from the cache if their content is discarded, although this automatic removal policy can be changed. If an NSDiscardableContent object is put into the cache, the cache calls discardContentIfPossible on it upon its removal.

来自 NSCache 类参考: NSCache 对象中存储的常见数据类型是实现 NSDiscardableContent 协议的对象。将这种类型的对象存储在缓存中是有好处的,因为它的内容在不再需要时可以被丢弃,从而节省内存。默认情况下,如果缓存中的 NSDiscardableContent 对象的内容被丢弃,它们会自动从缓存中删除,尽管可以更改此自动删除策略。如果一个 NSDiscardableContent 对象被放入缓存,缓存会在它被移除时调用discardContentIfPossible。