【发布时间】:2017-03-25 04:04:40
【问题描述】:
所以在:
- How do I set a auto increment key in Realm?
- Realm and auto increment Behavior (Android)
- https://github.com/realm/realm-java/issues/469
它说,Realm 不支持主键自动增量。好的,所以我想自己添加。链接的帖子显示了这样做的方法。
问题:建议的解决方案需要自己为每个模型类手动添加 getNextPrimaryId() 函数。这样做似乎非常愚蠢。我尝试自己在 Swift 中编写一个通用的,所以我只需要这样做一次,它会自动应用于我的所有模型类,但我失败了 - 因为我在 Swift 中不是那么好。
尝试 1:
extension Object {
func autoIncId() -> Int {
let objects = Database.realm.objects(self).sorted("id")
// Filter the max id here and return + 1
}
}
尝试 2:
class Database {
static func autoIncId(type: Object) -> Int {
let currentId = Database.realm.objects(type.self).map{$0.id}.maxElement ?? 0
return currentId + 1
}
}
两者都没有编译,因为 "Cannot convert value of type "Object" to expected argument type "Object.Type"".
有人知道如何编写自动适用于所有模型的通用函数吗?我只是想打电话给MyModelClass.autoIncId() 来获取下一个ID...
【问题讨论】: