Sam Mason
Sam Mason

Reputation: 1037

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!

Upvotes: 3

Views: 2362

Answers (1)

David Wong
David Wong

Reputation: 10294

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:"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
}

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: https://github.com/Haneke/HanekeSwift

Upvotes: 4

Related Questions