有人可以举例说明如何使用NSCache
缓存字符串吗?还是有人有一个很好的解释链接?我似乎找不到任何..
有人可以举例说明如何使用NSCache
缓存字符串吗?还是有人有一个很好的解释链接?我似乎找不到任何..
Answers:
使用方法与使用方法相同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];
}
applicationDidEnterBackground
)
NSCache
对象没有被释放,那么可以,它将保留在内存中。但是,其内容可能仍会被剔除。
@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"];
在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"
class Cache: NSCache<AnyObject, AnyObject> { static let shared = NSCache<AnyObject, AnyObject>() private override init() { super.init() } }
缓存的对象不应该实现NSDiscardableContent协议吗?
从NSCache类参考中:存储在NSCache对象中的常见数据类型是实现NSDiscardableContent协议的对象。将此类对象存储在缓存中有很多好处,因为可以在不再需要它的内容时将其内容丢弃,从而节省了内存。默认情况下,如果丢弃了缓存中的NSDiscardableContent对象,则它们的内容将被自动删除,尽管可以更改此自动删除策略。如果将NSDiscardableContent对象放入缓存,则缓存在删除后会对其调用discardContentIfPossible。