谁能给出一个如何使用NSCache缓存字符串的例子?或者任何人有链接到一个很好的解释?我好像找不到任何..
发布于 2011-04-22 21:56:14
使用它的方式与使用NSMutableDictionary的方式相同。不同的是,当NSCache检测到过多的内存压力(即它缓存了太多的值)时,它会释放其中的一些值来腾出空间。
如果您可以在运行时重新创建这些值(通过从互联网下载,进行计算,等等),那么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];
}发布于 2012-10-18 22:33:12
@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"];发布于 2015-01-02 10:47:49
在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"要创建单个应用程序范围的NSCache实例(单例),您可以轻松地扩展NSCache以添加sharedInstance属性。只需将以下代码放在一个名为NSCache+Singleton.swift的文件中:
import Foundation
extension NSCache {
class var sharedInstance : NSCache {
struct Static {
static let instance : NSCache = NSCache()
}
return Static.instance
}
}然后,您可以在应用程序中的任何位置使用缓存:
NSCache.sharedInstance.setObject("String for key 2", forKey: "Key2")
var result2 = NSCache.sharedInstance.objectForKey("Key2") as String
println(result2) // Prints "String for key 2"https://stackoverflow.com/questions/5755902
复制相似问题