tags:

views:

83

answers:

1

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.

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