Search code examples
iosobjective-ccore-dataobject-relationships

Core Data Relationships and saving/fetching


I'm a little confused about the core data mechanisms with respect to object relationships.

I have an "Account" model, and a "Credit Card" model, and I have two questions:

  1. How do I set up a one-to-many relationship from Account to Credit Card and a one-to-one relationship from Credit Card to Account? I'm having trouble figuring out exactly how to set that from the data model in XCode.
  2. If my Account model has a Credit Card property (or an NSSet, it looks like), and I set that property and save the account object, should the Credit Card object associated with it be saved as well? Or does that need to be saved separately? What's the proper way to do this? Conversely, what's the proper way to fetch objects in such a relationship, and to modify and replace them in the core data store, rather than simply inserting?

I know these are pretty basic core data questions, so thank you in advance for your patience.


Solution

    1. You need to read this guide. Probably you should change the display style in Xcode to be table based rather than the diagram style.

    2. You don't save individual objects, you save the store as a whole. So all changes are saved at the same time.

    When you have an object with a relationship it is presented to you as a set (NSSet as you say). You can iterate that set to find and modify the destination objects, you can also filter the set to find specific objects. You can also run fetch requests with predicates to find the objects you want to modify. There are many options.