Realm.io和复合主键

时间:2015-08-17 16:46:27

标签: ios swift entity realm

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

2 个答案:

答案 0 :(得分:11)

看来这是在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"

答案 1 :(得分:5)

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

取自&#34; mrackwitz&#34;在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)"
    }
}
相关问题