ios - iOS 上 api 响应缓存的最佳策略

标签 ios api http-caching

如果我对 api 端点执行简单请求以获取一些数据。这些数据是缓存在磁盘上的任何地方还是每次都获取新鲜数据?

如果它每次都获取是不是很糟糕?我是否应该缓存它并创建某种方法来检查它是否已在某处服务器上更新!

最佳答案

每次您从服务器请求它时,它都会被检索。

如果需要,您可以使用 NSCache 来缓存项目,它的工作方式类似于 NSDictionary。

// Init it and iVar it somewhere
self.cache = [NSCache new];

id object = [self.cache objectForKey:"http://www.someURL.com/with/a/path"]
if object == nil {
  //perform your fetch here
  //after the fetch is preformed...
  [self.cache setObject: dataObject forKey:"http://www.someURL.com/with/a/path"];
  //perform what you need to with said object
} else {
  //perform operation with cached object
}

使用 NSCache 的原因是,如果内存不足,它会自行清除。

如果您使用的是 Swift,这里有一个不错的库: https://github.com/Haneke/HanekeSwift

关于ios - iOS 上 api 响应缓存的最佳策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32129728/

相关文章:

java - 在 IBM SDK 之上使用 Sun JCE 提供程序

ios - 从 UicollectionView Controller 传递数据时出现问题

ios - swift:如何设置类以在没有 Storyboard 的情况下查看 Controller ?

c# - servicestack GlobalRequestFilters 请求 Dto 为 null

http - Cache-Control 是 :must-revalidate obliging to validate all requests, 还是陈旧的?

ruby-on-rails-3 - Heroku 和 Rails - Varnish HTTP 缓存不起作用

javascript - 根据 Google PageSpeed Insights 建议,利用 maps.googleapis 浏览器缓存

ios - 证书有效时 InvalidApnsCredential

iphone - 从 AVAssetReaderOutput 读取数据时 iOS 5.0 崩溃

json - 使用 REST 发送列表/表格数据 JSON 的正确方法是什么?