Realm.io和复合主键

sty*_*972 9 entity realm ios swift

我正在使用Realm for Swift 1.2,我想知道如何为实体实现复合主键.

因此,您可以通过覆盖来指定主键 primaryKey()

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

我能看到的唯一方法就是创建另一个复合属性

var key1 = "unique thing"
var key2 = 123012

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

override static func primaryKey() -> String? {
    return "key"
}
Run Code Online (Sandbox Code Playgroud)

你如何在Realm中正确提供复合键?

小智 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"
Run Code Online (Sandbox Code Playgroud)


Roe*_*e84 5

正确答案需要更新(关于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)"
    }
}
Run Code Online (Sandbox Code Playgroud)