Sam Mason Sam Mason - 1 year ago 107
iOS Question

Best strategy for api response caching on iOS

If I performed a simple request to an api endpoint to fetch some data. Does this data get cached on disk anywhere or does it fetch it fresh every time?

If it fetches every time is this bad? Should I be caching it and create some way of checking if its been updated on the server somewhere!

Answer Source

It will get retrieved each time you request it from your the server.

You can use NSCache to cache items if you want, it works like an NSDictionary.

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

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

The reason to use NSCache is that it will flush itself out if you run into low memory.

If you're using Swift, there's a nice library here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download