【问题标题】:Realm.io and compound primary keysRealm.io 和复合主键
【发布时间】:2015-08-17 16:46:26
【问题描述】:

我正在使用 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 中正确地提供复合键?

【问题讨论】:

    标签: ios swift entity realm


    【解决方案1】:

    看来这是在 Realm 中返回复合键的正确方法。

    这是来自 Realm 的答案:https://github.com/realm/realm-cocoa/issues/1192

    您可以使用lazy 和didSet 的组合来代替compoundKey 属性被派生和存储:

    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"
    

    【讨论】:

    • 来自 jpsim 在领域 github:“一旦这些对象被持久化,领域实际上不会调用 willSet 和 didSet,因此您必须使用自定义设置器”
    • "从 Realm Swift 1.0.1 开始,由于与 Objective-C 运行时的互操作性问题,您不能再使用惰性属性"github.com/realm/realm-cocoa/issues/1192#issuecomment-323322317
    【解决方案2】:

    正确答案需要更新(关于 didSet 和lazy)

    取自 Realm git-hub 的“mrackwitz”: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)"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多