Grumme
Grumme

Reputation: 806

Auto increment ID in Realm, Swift 3.0

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

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

Any suggestions how i can fix this?

My incrementID and primaryKey function as they look right now.

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

Upvotes: 9

Views: 13438

Answers (2)

rahim Ios Developer
rahim Ios Developer

Reputation: 1

    use this below example code.
    
    class Dog: Object {
            @Persisted(primaryKey: true) var id: Int?
            @Persisted var name: String?
            @Persisted var age: Int?
            
            func incrementID() -> Int {

let realm = try! Realm()
                let getvalue = realm.object(Dog.self).map({$0.id!}).last ?? 0
                return getvalue + 1
            }
        }
        
        let dog = Dog()
                dog.name = "Rex"
                dog.age = 1
                dog.id = dog.incrementID()
        
        its keep increase its value in ID

Upvotes: 0

Thomas Goyne
Thomas Goyne

Reputation: 8138

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

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

Upvotes: 35

Related Questions