dwaz
dwaz

Reputation: 664

Linking Realm Data Instead of Copying

I have a lookup table (Book) in a Realm db that contains objects that can be referenced from other objects (Person in the below example). This lookup table (Book) has a primary key (id), and I get this error when I try to add a record that references the lookup table:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Can't set primary key property 'id' to existing value 'xxx1234'

Here is some example code:

// Models:    
class Book: Object {
    dynamic var id: String = ""
    dynamic var title: String = ""

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

class Person: Object {
    dynamic var name: String = ""
    let booksRead = List<Book>()
}

// Controller Code:
func selectBooks(books: [Book]){
    for book: Book in books {
        self.person.booksRead.append(book);
    }
    let realm = try! Realm();
    try! realm.write{
        realm.add(self.person);
    }
}

When the selectBooks method runs with an array of books, realm tries to create new books for the ones the user selected.

How do I get realm to add the books as references to the existing books and not try to create new books?

Upvotes: 0

Views: 548

Answers (1)

ast
ast

Reputation: 526

How about adding the object to the Realm before you insert it in the list:

for book: Book in books {
    self.realm.add(book, true)
    self.person.booksRead.append(book)
}

If you use the add method it will handle duplicates and just update the object if it already exists. Here is the doc entry: https://realm.io/docs/swift/latest/api/Classes/Realm.html#/s:FC10RealmSwift5Realm3addFS0_FTCS_6Object6updateSb_T_

Upvotes: 2

Related Questions