I found this great solution for using Realm with compound primary key in Swift: https://github.com/realm/realm-cocoa/issues/1192
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)"
}
}
But I discovered that Realm does not support lazy properties, in my case I receive this error:
exception NSException * name: "RLMException" - reason: "Lazy managed property 'compoundKey' is not allowed on a Realm Swift object class. Either add the property to the ignored properties list or make it non-lazy." 0x00007f8a05108060
Is it still possible to have compound key without lazy property?
The solution you found is outdated. I'll leave a note about that there. I'd suggest removing the lazy
modifier and initializing compoundKey
to an empty string.
来源:https://stackoverflow.com/questions/38010548/compound-key-in-realm-with-lazy-property