带 OR 运算符的领域主键

Realm Primary key with OR operator

我正在为我的新应用程序使用 RealmSwift。我的领域 class 有两个主键。 举个例子,我有一个像这样的领域模型(产品):-

class Product: Object, Mappable {

    dynamic var id: String? = nil
    dynamic var tempId: String? = nil
    dynamic var name: String? = nil
    dynamic var price: Float = 0.0
    dynamic var purchaseDate: Date? = nil

    required convenience init?(map: Map) {
        self.init()
    }

    //I want to do something like this
    override static func primaryKey() -> String? {
        return "id" or "tempId"
    }

    func mapping(map: Map) {
        id <- map["_id"]
        tempId <- map["tempId"]
        name <- map["name"]
        price <- map["price"]
        purchaseDate <- (map["purchaseDate"], DateFormatTransform())
    }

因此我在我的设备中创建了一个领域对象并使用主键 tempId 存储到领域数据库中,因为实际的主键是 id,这是服务器生成的主键是仅在报告同步后出现。因此,当我使用那些 tempId 向服务器发送多个报告时,服务器响应我返回与每个 tempId 映射的实际 id。由于报告不仅是从我这边创建的,所以我不能将 tempId 保留为主键。我想到了Compound primary key,但不能解决问题

所以我想创建一个主键,例如 If id is there then that is the primary key else tempId is the primary key.

如何操作?

您本质上需要的是计算的 属性 作为主键。但是,目前不支持,只有存储和管理的领域属性可以用作主键。一种解决方法是定义 idtempId 以具有显式 setter 函数,并且在 setter 函数中您还需要设置另一个存储的 属性,它将是您的主键。

如果您想更改 idtempId,请不要以通常的方式进行,而是通过它们的 setter 功能进行。

想法取自 this GitHub 问题。

class Product: Object {
    dynamic var id:String? = nil
    dynamic var tempId: String? = nil

    func setId(id: String?) {
        self.id = id
        compoundKey = compoundKeyValue()
    }

    func setTempId(tempId: String?) {
        self.tempId = tempId
        compoundKey = compoundKeyValue() 
    }

    dynamic var compoundKey: String = ""
    override static func primaryKey() -> String? {
        return "compoundKey"
    }

    func compoundKeyValue() -> String {
        if let id = id {
            return id
        } else if let tempId = tempId {
            return tempId
        }
        return ""
    }
}
dynamic private var compoundKey: String = ""

required convenience init?(map: Map) {
  self.init()
  if let firstValue = map.JSON["firstValue"] as? String,
    let secondValue = map.JSON["secondValue"] as? Int {
    compoundKey = firstValue + "|someStringToDistinguish|" + "\(secondValue)"
  }
}