一尘不染

复合主键领域/交换

swift

我是快速入门的新手。我想做一个复合主键,当我尝试这样的事情时:

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’

任何人都可以通过示例为我提供帮助,该示例如何创建复合主键?


阅读 245

收藏
2020-07-07

共1个答案

一尘不染

对于1.0.1+领域:

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

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

    func setup(id: Int, tourId: Int){
        self.id = id
        self.tourId = tourId
        self.compoundKey = compoundKeyValue()
    }

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

用法示例:

let location = DbLocation()
location.setup(id: 0, tourId: 1) 
print(location.compoundKey) // "01"

当然,你可以玩弄各种使用didSet上的听众idtourId,以确保compoundKey才能正确重写每一个值换衣服的时间。

对于pre-1.0.1领域:

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

自定义设置器确保compoundKey始终处于更新状态,惰性关键字确保您第一次访问它时,它将从您已设置的内容中派生。

在此问题进行了辩论的线程中查找有关此主题的更多信息。

2020-07-07