A Core Data Primer

Everyone’s first encounter with Core Data would be through books and the occasional glance at the documentation. No one tells you what are the base tips in bullet points that you need to know.

Republished from an old Tumblr. Keeping this as a record of my past thoughts about things. These might not be current these days.

Everyone’s first encounter with Core Data would be through books and the occasional glance at the documentation. No one tells you what are the base tips in bullet points that you need to know. Having worked on Core Data for the past 9 months, I thought it’ll be a service to the community to at least commit something to Google’s memory.

  • Create NSManagedObjectContext in new threads prior to using them. Pass them the NSPersistentStoreCoordinator of any NSManagedObjects across threads is fine.
  • NSManagedObjectID is your friend. Always use it if you are doing threading.
  • NSManagedObjectID is sometimes temporary. Use obtainPermanentObjectIDs to ensure that they are permanent.
  • Getting a permanent ID might cost disk access so use wisely.
  • Process cross context saving on the thread that the NSManagedObjectContext was created.
  • Instrument’s time profiler is your friend to find where Core Data calls are taking a long time.
  • Additionally, you can also get SQL statements that are generated as debug messages in console by turning on a flag.
  • Use as little relationships as possible when fetching objects. Easier to fetch criteria based on the actual operating object and have the fetch also fetch all relationships.
  • Sometimes it is easier to spin off a thread to fetch results and process them before calling the completion block with results.
  • Have a manager to handle all Core Data fetching of objects instead of being smart and trying to have individual managed object subclasses handle everything.
  • NSFetchedResultsController is sometimes a bitch when sending notifications of changed content. Don’t use UITableView’s reloadSectionsWithAnimation and its siblings when crashy happens.
  • Don’t look into [NSManagedObjectContext registeredObjects] to get objects back. They might already have been deleted but still cached.
  • Always test Core Data performance on device.
  • Always do fetches on entities that you are filtering criteria for then use inverse relationships that are prefetched to get the data you really want (Basically think topsy turvy; less database joins the better because this is an object graph).