NSFetchedResultsController Cache

190 Views Asked by At

I wanted to know the importance of Caching the FetchedResultsController. Say I have a table view with 50 items to shows and at any given point of time the table view can show around 10 results. As and when I scroll the table view up and down, does the FetchedResultsController fetch implicitly and cache the results? And If I don't cache or specify the cache, does the FetchedResultsController needlessly do a fetch again. In a nutshell, I am wondering about the caching feature of FetchedResultsController.

2

There are 2 best solutions below

1
On

These are the things that happen when you specify a cache name:

  • If the controller can’t find an appropriate cache, it calculates the required sections and the order of objects within sections. It then writes this information to disk.
  • If it finds a cache with the same name, the controller tests the cache to determine whether its contents are still valid. The controller compares the current entity name, entity version hash, sort descriptors, and section key-path with those stored in the cache, as well as the modification date of the cached information file and the persistent store file.
  • If the cache is consistent with the current information, the controller reuses the previously-computed information.
  • If the cache is not consistent with the current information, then the required information is recomputed, and the cache updated.

Any time the section and ordering information change, the cache is updated.

In particular cache is used to store the information related to section and indexpath that makes loading of data fast.

0
On

The main reason for the cache is so the app re-launches faster because it doesn't need to re-fetch the records which it already did the last time the app was running. The results are instead stored in a file already in the structure for the table so can load instantly compared to the many multiple queries needed to load all the rows, group them etc. Also what is pretty cool is if another process or extension has edited the database, then when the app first appears it will match the default image (the screenshot taken when app was last closed) and it will animate the changes to the table that happened while the app wasn't running. This is great for the user understanding the context.

You can also use it if you go in a view controller, then back, then in again, it can be faster to show a table.