Maraj Hussain
Maraj Hussain

Reputation: 1596

What is the better approach to insert data in Realm?

I am using Realm as a database in my application for storing data locally.
I am confused with the data insertion method in it.
My question is that which one is better for inserting data in Realm insert(), createObject(), copyToRealm() and copyToRealmOrUpdate().
Thanks in advance.

Upvotes: 2

Views: 2289

Answers (1)

nkirit
nkirit

Reputation: 389

Assuming that you have an integer as the primary key.

Then 0 is the default value for int fields, so if you have a RealmObject with 0 as the value then, it means that realm.createObject(YourRealmClass.class) will fail with the error mentioned below.

RealmPrimaryKeyConstraintException: Value already exists: as it will create an object with the default value.

What is the better way to create RealmObjects?

copyToRealmOrUpdate() or insert(). I will recommend you that use copyToRealmOrUpdate() because it is always better to use as it first checks if record exists. If record exists then it will update if record does not exits it will insert new record .

Upvotes: 2

Related Questions