Tyler
Tyler

Reputation: 19848

Realm.io and compound primary keys

I'm using Realm for Swift 1.2, and I'm wondering how to implement a compound primary key for an entity.

So you specify your primary key by overriding primaryKey()

override static func primaryKey() -> String? { // <--- only 1 field
    return "id"
}

The only way I can see is to create another compound attribute like so

var key1 = "unique thing"
var key2 = 123012

lazy var key: String? = {
    return "\(self.key1)\(self.key2)"
}()

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

How do you properly supply compound keys in Realm?

Upvotes: 10

Views: 5863

Answers (2)

Witterquick
Witterquick

Reputation: 6150

The correct answer needs an update (regarding didSet and lazy)

Taken from "mrackwitz" at Realm git-hub: https://github.com/realm/realm-cocoa/issues/1192 :

public final class Card: Object {
    public dynamic var id = 0
    public func setCompoundID(id: Int) {
        self.id = id
        compoundKey = compoundKeyValue()
    }
    public dynamic var type = ""
    public func setCompoundType(type: String) {
        self.type = type
        compoundKey = compoundKeyValue() 
    }
    public dynamic var compoundKey: String = "0-"
    public override static func primaryKey() -> String? {
        return "compoundKey"
    }

    private func compoundKeyValue() -> String {
        return "\(id)-\(type)"
    }
}

Upvotes: 7

chimpymike
chimpymike

Reputation: 166

It appears that is the correct way to return a compound key in Realm.

Here's the answer from Realm : https://github.com/realm/realm-cocoa/issues/1192

You could use a mix of lazy and didSet instead to have the compoundKey property be both derived and stored:

public final class Card: Object {
    public dynamic var id = 0 {
        didSet {
            compoundKey = compoundKeyValue()
        }
    }
    public dynamic var type = "" {
        didSet {
            compoundKey = compoundKeyValue()
        }
    }
    public dynamic lazy var compoundKey: String = self.compoundKeyValue()
    public override static func primaryKey() -> String? {
        return "compoundKey"
    }

    private func compoundKeyValue() -> String {
        return "\(id)-\(type)"
    }
}

// Example

let card = Card()
card.id = 42
card.type = "yolo"
card.compoundKey // => "42-yolo"

Upvotes: 11

Related Questions