I have a method ‘books’ in my view controller that fetches all the books in core data and returns an array of them. I am relying on self.books often – when I need to know which book it is at certain index, how many books there are, etc, the books method re-fetches the results.
Would I gain any performance improvements by caching these results in an iVar? The vast majority of the time I know that the result of self.books is not going to change (objectAtIndex, count, etc). I could add a second boolean iVar ‘booksNeedRefresh’ to act as a dirty flag, and set it to true only if I add/delete a book. self.books could then check this flag and only re-fetch when necessary.
I guess my questions are:
- Does each fetch request from core data introduce a non-negligible performance hit?
- Is caching + a dirty flag a sensible solution?
I think you are on the wrong track. Core Data already provides you with a lot of memory management, so there is not need for “dirty” flags etc.
The most obvious solution is to use a
NSFetchedResultsController. Its main purpose is to display data in a table view while keeping the memory footprint small – but it can be used for other purposes as well. Your books array would become_fetchedResultsController.fetchedObjects, and the FRC will take care of the optimization between memory and fetches.To answer your question in principle, the above tradeoff is exactly the issue, so you are correct in thinking about that. Frequent fetches do have performance implications.