复合主键领域/ swift

问题描述 投票:20回答:4

我是快速和领域的新手。我想制作一个复合主键,当我尝试这样的事情时:

class DbLocation : Object {
 dynamic var id = 0
 dynamic var tourId = 0

 dynamic var uuid : String  {
    return "\(id)\(tourId)"
 }

 override static func primaryKey() -> String? {
    return "uuid"
 }
}

我收到此错误:'对象'DbLocation'上不存在主键属性'uuid'

任何人都可以帮我解决如何创建复合主键的示例?

ios swift realm
4个回答
25
投票

这应该给你答案:

class DbLocation: Object {
    dynamic var id = 0
    dynamic var tourId = 0

    func setCompoundID(id: Int) {
        self.id = id
        compoundKey = compoundKeyValue()
    }

    func setCompoundTourId(tourId: Int) {
        self.tourId = tourId
        compoundKey = compoundKeyValue()
    }

    dynamic lazy var compoundKey: String = self.compoundKeyValue()

    override static func primaryKey() -> String? {
        return "compoundKey"
    }

    func compoundKeyValue() -> String {
        return "\(id)\(tourId)"
    }
}

自定义setter确保复合键始终更新,懒惰关键字确保您第一次访问它时,它将从您已设置的内容中派生出来。

有关此主题的更多信息,请参阅this thread,此问题一直存在争议。


1
投票

简单地创建一个新属性,其值设置为您希望为复合主键的其他属性。

class DbLocation: Object {
            dynamic var id = 0
            dynamic var tourId = 0
            dynamic var compoundKey: String? = ""

        override static func primaryKey() -> String? {
                return "compoundKey"
            }
        }
    let location = DbLocation()
    location.tourId = 1
    location.id = 5
    location.compoundKey = "\(id) \(tourId)"

0
投票

对于Swift和Realm的最新版本,我会做这样的事情。

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

-6
投票

你需要从你的对象中返回一个属性

这是示例代码

class FoodModel:Object
{
    dynamic var name = ""
    dynamic var _id  = ""


    override static func primaryKey() -> String? {
        return "_id"
    }
}

请注意,_id在模型中是var

© www.soinside.com 2019 - 2024. All rights reserved.