我正在使用 Realm for Swift 1.2,我想知道如何为实体实现复合主键。
因此您可以通过覆盖 primaryKey()
override static func primaryKey() -> String? { // <--- only 1 field
return "id"
}
我能看到的唯一方法是像这样创建另一个复合属性
var key1 = "unique thing"
var key2 = 123012
lazy var key: String? = {
return "\(self.key1)\(self.key2)"
}()
override static func primaryKey() -> String? {
return "key"
}
如何在 Realm 中正确提供复合键?
最佳答案
这似乎是在 Realm 中返回复合键的正确方法。
这是来自 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"
关于ios - Realm.io 和复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055663/