我正在为我的新应用程序使用 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 属性可以用作主键。一种解决方法是定义 id
和 tempId
以具有显式 setter 函数,并且在 setter 函数中您还需要设置另一个存储属性,这将是您的主键。
如果你想改变 id
或 tempId
不要用通常的方式来做,而是通过它们的 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/