ios - Realm.io 和复合主键

标签 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 中正确提供复合键?

最佳答案

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

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

You could use a mix of lazy and didSet instead to have the compoundKey property be both derived and stored:

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"

关于ios - Realm.io 和复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055663/

相关文章:

ios - UITextField 在 iOS 14 中抛出各种错误

ios - 使用 collectionView.isPagingEnabled = true 如何知道分页何时完成

swift - 获取 UIView/UIImageView 的特定角坐标,而不管其旋转

ios - 全局背景颜色变化

oop - 单一职责原则和实体类

iphone - 在 iPhone 3G 上更新 iOS

ios - 如何控制 UIViewController 的 View 框架

ios - 删除不存在的 key 时,Firebase 数据库不会返回错误

hibernate - Hibernate 填充的 POJO 是实体、业务对象还是数据传输对象?

java - 在 JDOM/DOM 中禁用 XML 实体解析