David David - 9 months ago 72
iOS Question

Should I define the primary key for each entity in Realm?

I have noticed that setting PK is not obligatory in Realm and simply can be omitted. But in documentation is stated that:

Indexes are created automatically for primary key properties.

And I'd like to clear up some questions:

1) What is the default value for PK is defined by Realm, if I don't assign it by myself. Is it hash or whatever ? (If I don't set PK and call
[MyRealmObject primaryKey]
it returns

2) If this implicit PK is indexed by default ? Should I worry about it, because if it is not indexed, does it mean that it affects the general performance of this Entity (for example,fetching objects) ?

3) Is it a good practice to define PK every time for each
subclass or it isn't necessary for Realm and simply may rely on it's internal realization defined by Realm itself?

Answer Source

(Disclaimer: I work for Realm.)

Yep! Setting a primary key in Realm isn't obligatory, nor necessary, which is why it's completely up to the developer and the requirements of the app to determine whether it's necessary or not in their implementation.

In response to your questions:

1) There are no default values; you specify one of your own properties as a primary key. primaryKey returns nil by default since you need to override that yourself in order to indicate to Realm which property you want to act as a primary key. Some users have set integers as primary keys, but more often than not, using a UUID string is the most common.

2) There's no implicit primary key. You must use the [RLMObject primaryKey] method to explicitly state which property is the primary key, and THEN it will be indexed. :)

3) In my own (spare-time) development experience, I usually find having a primary key makes it a lot easier to identify and handle specific objects. For example, if you're passing an object across threads, you can simply pass the primary key value and use [RLMObject objectForPrimaryKey:] to refetch the object. Obviously this depends on your own implementation requirements. You probably shouldn't add a primary key unless you find out you really need one.

As an example, here's what you would add to your RLMObject subclass if you wanted to set a UUID string as a primary key:

@interface MyObject : RLMObject

@property NSString *uuid;


@implementation MyObject

+ (NSString *)primaryKey
   return @"uuid";

+ (NSDictionary *)defaultPropertyValues
   @{@"uuid": [[NSUUID UUID] UUIDString]};


I hope that helped!