或任何人有一个链接到良好的解释?我似乎找不到任何..解决方法 你使用它与使用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];}总结
以上是内存溢出为你收集整理的ios – 如何使用NSCache全部内容,希望文章能够帮你解决ios – 如何使用NSCache所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)