有人可以举一个使用NSCache
缓存字符串的例子吗?
或者有没有好的解释链接?我似乎找不到任何相关的信息。
有人可以举一个使用NSCache
缓存字符串的例子吗?
或者有没有好的解释链接?我似乎找不到任何相关的信息。
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];
}
applicationDidEnterBackground
之后) - barfoonNSCache
对象没有被释放,那么它将会一直存在于内存中。但是,它的内容仍然可能会受到削减。 - Jonathan Grynspan@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"
static let shared = NSCache()
private override init() { super.init() }
}```
(说明:这是一段 Swift 代码,定义了一个名为 `Cache` 的类和一个名为 `shared` 的静态属性,用于存储缓存数据。)
- AmitaiB缓存对象不应该实现NSDiscardableContent协议吗?
从NSCache类参考中可以看到: 在NSCache对象中存储的常见数据类型是实现NSDiscardableContent协议的对象。将这种类型的对象存储在缓存中有益处,因为当它们不再需要时,其内容可以被丢弃,从而节省内存。默认情况下,如果缓存中的NSDiscardableContent对象的内容被丢弃,则会自动从缓存中删除这些对象,尽管可以更改此自动删除策略。如果将NSDiscardableContent对象放入缓存中,则在其被移除时,缓存会调用discardContentIfPossible方法。