Realm.io and composite primary keys

I am using Realm for Swift 1.2, and I am wondering how to implement a composite primary key for an object.

So you specify your primary key, 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

 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 correctly supply composite keys in Realm?

+7
ios swift entity realm
source share
2 answers

This seems to be the right way to return the composite key in Realm.

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

Instead, you can use a combination of lazy and didSet to have the compositionKey property should be both derived and saved:

 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" 
+9
source share

The correct answer requires updating (regarding didSet and lazy)

Adapted from "mrackwitz" in 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)" } } 
+3
source share

All Articles