0

In Realm, what's the right way of creating a new object, without creating a new object for one of its relations?

Let's say I have the object Person with a one-to-one relation to the Job entity.

My code writes first 10 Jobs objects and then creates 10 other Person objects with the previously created objects.

Since the Person didn't exist before, the flag for update is false.

realm.add(person, update: false)

But since the Job object already existed it throws the follow exception:

Terminating app due to uncaught exception 'RLMException'.'Can't set primary key property '' to existing value ''.'

Idan
  • 5,405
  • 7
  • 35
  • 52
Felipe Peña
  • 2,712
  • 4
  • 22
  • 41

1 Answers1

0

It seem that you are trying to define a Realm object with primary key, but you didn't modify the key value.

For example:

class User: Object {
  dynamic var user    = ""
  dynamic var year    = ""
  dynamic var id      = ""
  dynamic var workouts = 0

  override static func primaryKey() -> String? {
    return "id"
  }
}

if you don't set the id value, you will get the following message:

Terminating app due to uncaught exception 'RLMException'.'Can't set primary key property ' ' to existing value ' '.'

There are several ways to solve it:

  1. Don't use primary key (not really recommended)
  2. Make sure you set the id when creating an Object
Community
  • 1
  • 1
Idan
  • 5,405
  • 7
  • 35
  • 52