Sam Mason Sam Mason - 1 month ago 4x
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!


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: