I used to create a column called 'id' which is auto incremented in any table I create. While in some cases I found that this column is useless while another column like 'citizen_ssn' is a better candidate to be the primary key.
So, what is the best practice in choosing the table's primary key ? Should I use what will fit the need or create the auto-incremented column or another opinion ?
In Realm
there is no real reason to have an auto-increment primary key. (although if your server returns primary key info, then it's useful to know that you're referring to the same object).
In SQLite (or any relational database) the reason you need them is that that is the only way you can link two objects together (through JOINs) - for example, a many-many relationship is done with a Join Table that contains the primary key of both linked tables as a foreign key.
In Realm, you can link objects together as a field like private OtherObject otherObject;
, and many relation as private RealmList<OtherObject> otherObjects
. So you don't need primary key to create relationship.
What you might need them for in Realm is if you want to use insertOrUpdate()
method to update an existing object in Realm by its primary key, overwriting it with an unmanaged object. You can also edit objects by calling the managed object's setters, so this is not entirely necessary.