如何使用NSCache

Thy*_*hys 120 xcode cocoa objective-c ios nscache

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

Jon*_*pan 133

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

如果您可以在运行时重新创建这些值(通过从Internet下载,通过计算,无论如何),那么NSCache可能适合您的需求.如果无法重新创建数据(例如,它是用户输入,它是时间敏感的等等),那么你不应该将它存储在一个NSCache因为它将在那里被销毁.

例如,不考虑线程安全性:

// 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];
}
Run Code Online (Sandbox Code Playgroud)

  • 它不是磁盘上的永久缓存.它只在内存中,所以是的,它会在你的应用程序停止运行时被破坏. (14认同)
  • 不是.断言断言某些事情是真的,即内部的陈述是真实的.我们断言对象分配和/或创建是成功的. (3认同)

Gab*_*ana 19

@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"];
Run Code Online (Sandbox Code Playgroud)

  • 是.保存:[imagesDictionary setObject:imageData forKey:@"KEY"]; retrieve:NSData*imageData = [imagesCache objectForKey:@"KEY"]; (3认同)
  • 将数据保存到chache:[imagesCache setObject:imageData forKey:@"KEY"]; (2认同)

Poi*_*Two 8

在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"
Run Code Online (Sandbox Code Playgroud)

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

import Foundation

extension NSCache {
    class var sharedInstance : NSCache {
        struct Static {
            static let instance : NSCache = NSCache()
        }
        return Static.instance
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 你知道如何在swift 3中实现这个吗? (3认同)
  • 这应该工作:```类Cache:NSCache <AnyObject,AnyObject> {static let shared = NSCache <AnyObject,AnyObject>()private override init(){super.init()}}``` (3认同)

Aju*_*mal 6

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

[[CacheController storeInstance] setCache:@"object" forKey:@"objectforkey" ];
Run Code Online (Sandbox Code Playgroud)

你可以使用它设置任何对象

[[CacheController storeInstance] getCacheForKey:@"objectforkey" ];
Run Code Online (Sandbox Code Playgroud)

回顾

重要说明:NSCache类包含各种自动删除策略.如果您希望将数据缓存为永久数据,或者您希望在特定时间内删除缓存数据, 请参阅此答案.