Database Reference
In-Depth Information
“Cache” the ball
As you can probably imagine, grouping teams into sections is not a cheap
operation. There's no way to avoid iterating over every team.
It's not a performance problem in this case because there are only 32 teams to
consider but imagine what would happen if your data set were much larger. What if
your task were to iterate over 3 million census records and separate them by
state/province?
“I'd just throw that on a background thread!” might be your first thought. The table
view, however, can't populate itself until all sections are available. You might save
yourself from blocking the main thread, but you'd still be left looking at a spinner.
There's no denying that this operation is expensive. At a bare minimum, you should
only pay the cost once: figure out the section grouping a single time, and reuse
your result every time after that.
The authors of NSFetchedResultsController thought about this problem and came
up with a solution: caching. You don't have to do much to turn it on.
Head back to viewDidLoad and make the following modification to the fetched
results controller initialization, adding a value to the cacheName parameter:
fetchedResultsController =
NSFetchedResultsController (fetchRequest: fetchRequest,
managedObjectContext: coreDataStack . context ,
sectionNameKeyPath: "qualifyingZone" ,
cacheName: "worldCup" )
You specify a cache name to turn on NSFetchedResultsController 's on-disk section
cache. That's all you need to do! Keep in mind that this section cache is completely
separate from Core Data's persistent store, where you persist the teams.
Note: NSFetchedResultsController 's section cache is very sensitive to changes
in its fetch request. As you can imagine, any changes—such as a different
entity description or different sort descriptors—would give you a completely
different set of fetched objects, invalidating the cache completely. If you make
changes like this, you must delete the existing cache using
deleteCacheWithName: or use a different cache name.
Build and run the application a few times. The second launch should be a little bit
faster than the first. This is not the author's power of suggestion (psst, say “fast”
five times in a row); it is NSFetchedResultsController 's cache system at work!
 
Search WWH ::




Custom Search