xcode Realm 中的自动递增 ID,Swift 3.0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39579025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:16:52  来源:igfitidea点击:

Auto increment ID in Realm, Swift 3.0

iosswiftxcoderealm

提问by Grumme

After a lot of troubles, i finally got my code converted to Swift 3.0.

经过一番折腾,我终于把我的代码转换成 Swift 3.0。

But it seems like my incrementID function isn't working anymore?

但似乎我的 incrementID 函数不再起作用了?

Any suggestions how i can fix this?

有什么建议我可以解决这个问题吗?

My incrementID and primaryKey function as they look right now.

我的 incrementID 和 primaryKey 函数就像它们现在的样子。

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

func incrementID() -> Int{
    let realm = try! Realm()
    let RetNext: NSArray = Array(realm.objects(Exercise.self).sorted(byProperty: "id")) as NSArray
    let last = RetNext.lastObject
    if RetNext.count > 0 {
        let valor = (last as AnyObject).value(forKey: "id") as? Int
        return valor! + 1
    } else {
        return 1
    }
}

回答by Thomas Goyne

There's no need to use KVC here, or to create a sorted array just to get the max value. You can just do:

这里不需要使用 KVC,也不需要创建一个排序数组来获取最大值。你可以这样做:

func incrementID() -> Int {
    let realm = try! Realm()
    return (realm.objects(Exercise.self).max(ofProperty: "id") as Int? ?? 0) + 1
}