有人可以举例说明如何使用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];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)