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