Search code examples
swiftrealm

Copying object from one Realm to another fails on primary key conflict


I'd like to copy an object from one realm to another, but it's complaining that there is already an object with that primary key.

Details:

There are two different Realms in my app. One is stored in the Caches folder and the other is the default in the Documents folder. They have the same schema. I would like to copy an object from one Realm to the other. Following the guidelines in the docs, I'm using Realm().create(_:value:update:) to make the copy. When I pass in the story from the ContentRealm to be created in the UserRealm, I get an exception stating that an object with the primary key already exists. However, no instances of type Story exist yet in the UserRealm, so there should not be a primary key conflict. Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to create an object of type 'Story' with an existing primary key value '4'.'

Am I doing this wrong?

    // Copy the Story to the user database
    var userStory: Story?
    do {
        try userRealm.write {
            userStory = userRealm.create(Story.self, value:storyObjectFromContentRealm)
        }
    }
    catch {
        print("Could not copy story: \(error)")
    }

Solution

  • It turns out that I had a cyclical relationship buried in my object graph. Realm's documentation warned me about this, and I thought I was okay, but turns out I was not. After modifying the relationships, I am able to successfully make a copy of an object from one realm to another.

    If you're running into this issue, check your relationships.