How to use Core Data

Issue #741

Whenever I do Core Data, the Laws of Core Data @davedelong is always my northern star

Below are some of take aways from that post

1) Core Data is more than just SQLite wrapper, it manages objects, relationships, fetching, faulting, …
2) Having 2 context: 1 main and 1 background that are both backed by the persistent coordinator. In modern Core Data stack, NSPersistentContainer has default viewContext already, we just need another newBackgroundContext
3) Never use a fetched NSManagedObject outside its context’s queue.
4) The viewContext is for fetching NSManagedObject on the main queue, and those objects are meant for read only. All mutating operation should be in the background context.
5) Better, like I usually do, is to treat CoreData as a cache, and use plain old struct for UI. This reduces dealing with faulting and optional
6) Using struct that mirrors Core Data NSManagedObject, it looks verbose (you can use code generator or Sourcery for this) but it’s safer
7) A nice trick to quickly convert struct to NSManagedObject is to use reflection with Mirror. NSManagedObject subclasses from NSObject so it is key value compliant

Read more


Updated at 2021-01-20 05:46:47

Comments