Understanding data persistence

Whenever you want to persist a model with Core Data, you must insert a new NSManagedObject into an NSManagedObjectContext. Doing this does not immediately persist the model. It merely stages the object for persistence in the current NSManagedObjectContext. If you don't properly manage your managed objects and contexts, this is a potential source of bugs. For example, not persisting your managed objects results in the loss of your data once you refresh the context. Even though this might sound obvious, it could lead to several hours of frustration if you aren't aware of this and have bugs in managing your managed object context.

If you want to save managed objects correctly, you must tell the managed-object context to persist its changes to the persistent store coordinator. The persistent store coordinator will take care of persisting the data in the underlying SQLite database.

Extra care is required when you use multiple managed object contexts. If you insert an object in one managed object context and persist it, you will manually need to synchronize the changes into the other managed object contexts. Also, managed objects are not thread-safe. This means that you must make sure that you create, access, and store a managed object on a single thread at all times. The managed-object context has a helper method called perform(_:) to help you with this.

Inserting new objects, updating them, or adding relationships between objects should always be done using the perform(_:) method. The reason is that the helper method makes sure that all code in the closure you want to perform are executed on the same thread that the managed object context is on.

Now that you're aware of how data persistence works in Core Data, it's time to start implementing the code to store family members and their favorite movies. You will implement the family member persistence first. Then you'll expand the app so you can safely add movies to family members.