复合主键领域/ swift

时间:2015-07-07 10:09:51

标签: ios swift realm

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

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'

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

4 个答案:

答案 0 :(得分: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)"
    }
}

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

this thread中就此问题进行辩论,了解有关此主题的更多信息。

答案 1 :(得分: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)"

答案 2 :(得分: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)"
  }
}

答案 3 :(得分:-5)

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

这是示例代码

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


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

请注意,_id是模型中的var