ios - 如何使用 NSCache

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

最佳答案

您使用它的方式与使用 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];
}

https://stackoverflow.com/questions/5755902/

相关文章:

objective-c - "Receiver type ' CALayer' 例如消息是前向声明”

objective-c - Xcode 不显示导致崩溃的行

objective-c - 在 Objective-C 中将 NSArray 过滤成一个新的 NSA

ios - NSLocalizedString() 的第二个参数是什么?

objective-c - Swift 中的只读和非计算变量属性

iphone - 使用 CALayers 的圆形 UIView - 只有一些角落 - 如何?

iphone - 获取当前方法调用的线程id

ios - 如何将 NSAppTransportSecurity 添加到我的 info.plist

objective-c - iOS启动后台线程

objective-c - 在 Objective-C 中将 NSNumber 转换为 int