Search code examples
ioscore-datapersistent-storage

How are relationships in CoreData saved to the persistent store?


Using CoreData with an UIManagedDocument the persisten Store is a SQLite Database in the document at the saving file path. I read that CoreData produces its own primary key (integer values).

I have two questions concerning relationships in CoreData:

  1. As CoreData is an relational object orientated database I wonder how relationships between objects in entities are saved? Does CoreData use foreign key (e.g. entity one uses primary key of entity two as foreign key)?
  2. How are the relationships saved to the persistent store document? If you save for example an NSString or an NSDictionary (to a Binary Data) you can see those objects when opening the persistent store document.

Solution

  • It depends.

    For to-one relationships the primary key of the destination entity is stored as a foreign key in the table (row) of the entity.

    For to-many relationships a separate join table is created which stores the primary keys of the source and destination entities.

    FWIW this is easy enough to explore by using sqlite3 from the command line.

    $ sqlite3 cd.sqlite
    $ (SQLite) .schema
    

    That will reveal the join tables for your to-many relationships and you'll be able to see the foreign key columns for your to-one relationships.

    The same is true for the data / string columns. SQLite allows for both data and string (varchar) storage.