Right now whenever I need to access my data set size (and it can be quite frequently), I perform a countForFetchRequest on the managedObjectContext. Is this a bad thing to do? Should I manage the count locally instead? The reason I went this route is to ensure I am getting 100% correct answer. With Core Data being accessed from more than one places (for example, through NSFetchedResultsController as well), it's hard to keep an accurate count locally.
views:
83answers:
1
A:
-countForFetchRequest:
is always evaluated in the persistent store. When using the Sqlite store, this will result in IO being performed.
Suggested strategy:
- Cache the count returned from
-countForFetchRequest:
. - Observe
NSManagedObjectContextObjectsDidChangeNotification
for your own context. - Observe
NSManagedObjectContextDidSaveNotification
for related contexts.
For the simple case (no fetch predicate) you can update the count from the information contained in the notification without additional IO.
Alternately, you can invalidate your cached count and refresh via -countForFetchRequest:
as necessary.
Jim Correia
2009-07-31 13:58:41