0

So in:

  1. How do I set a auto increment key in Realm?
  2. Realm and auto increment Behavior (Android)
  3. https://github.com/realm/realm-java/issues/469

It says, that the Primary Key Auto Increment is not supported on Realm. OK, so I want to add that myself. The linked posts shows ways to do that.

Problem: The proposed solutions require to manually add a getNextPrimaryId() function for every model class myself. That seems extremely stupid to do. I tried to write a generic one myself in Swift so I only have to do that once and it will apply to all my model classes automatically, but I failed.

Attempt 1:

extension Object {
    func autoIncId() -> Int {
        let objects = Database.realm.objects(self).sorted("id")
        // Filter the max id here and return + 1
    }
}

Attempt 2:

class Database {    
    static func autoIncId(type: Object) -> Int {
        let currentId = Database.realm.objects(type.self).map{$0.id}.maxElement ?? 0
        return currentId + 1
    }
}

Both don't compile because "Cannot convert value of type "Object" to expected argument type "Object.Type"".

Does anyone have any idea how to write generic function that applies to ALL models automatically? I simply would like to just call MyModelClass.autoIncId() to get the next id.

MFerguson
  • 1,739
  • 9
  • 17
  • 30

1 Answers1

0

Assuming you're using Swift 3, you should use the following:

type(of: self)

However, why do you want an autoincrementing field? If you want a unique key, just use a UUID. Autoincrementing fields will cause you huge problems when you want your app to sync across multiple devices (eg. iPhone and iPad).

Michael
  • 8,891
  • 3
  • 29
  • 42
  • Hm, thanks. But that still leaves me with the problem that the compiler doesn't know about the "id" property, because "Object" doesn't have one. AFAIK there is no "get attribute from db of object xy" in Realm. So how can i get the id property of the selected object, if i can't access it via property because of compiler type restrictions? –  Nov 11 '16 at 00:44
  • You can get it, since Realm Objects inherit from NSObject - using `value(forKey:)`, so you would use `$0.value(forKey: "id")`. However, if you use the `sorted` method, you just have it as a string anyway. Nevertheless, I strongly suggest an autoincrementing property is a bad idea. – Michael Nov 11 '16 at 01:08