swift - 带 OR 运算符的 Realm 主键

标签 swift realm objectmapper

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

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())
    }

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

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

如何做到这一点?

最佳答案

您本质上需要的是一个作为主键的计算属性。但是,目前不支持,只有存储和管理的 Realm 属性可以用作主键。一种解决方法是定义 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 ""
    }
}

关于swift - 带 OR 运算符的 Realm 主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45632076/

相关文章:

java - 如何将 json 节点中的动态键映射到类?

ios - 无法使用对象映射器解析双字符串下方

swift - 在所有成员初始化之前被闭包自捕获

ios - 当我尝试将保存的数据更新到 Realm 时它崩溃了,图像在更新时变为零

xcode - 对象不存在时 ABRecordCopyValue 不起作用

javascript - 无法在 Realm + React Native 中修改写入事务错误之外的托管对象

ios - Realm 到 iOS addItem 刷新问题

ios - 如何使用 alamofire 对象映射器解析复杂数据?

Swift - 自定义文本输入 View

swift - 如何在 Swift 中创建带有起点和终点的线条(ARKit、SCENEKit)