How do I set a auto increment key in Realm?
Realm doesn't have auto increment behavior, so you'll need to manage that yourself. A question I'd encourage you to ask yourself about your data:
Is it necessary to have sequential, contiguous, integer ID's?
If not, then a unique string primary key might be sufficient. Then you can use something like [[NSUUID UUID] UUIDString]
to generate unique string ID's. The nice thing about this is that these UUID's are more or less guaranteed to be unique, even in multithreaded scenarios.
If so, it might be more efficient to always keep the last number in memory, so that queries aren't required every time a new ID should be generated. If objects might be created in multiple threads, make sure to make your nextPrimaryKey()
function thread-safe, otherwise it might generate the same number twice (or more!).
Autoincrement id Realm in Swift 2.0:insert code in class realm and object write use
import Foundationimport RealmSwiftclass Roteiro: Object {dynamic var id = 0dynamic var Titulo = ""dynamic var Observacao = ""dynamic var status = falsedynamic var cadastrado_dt = NSDate()override static func primaryKey() -> String? { return "id"}//Incrementa IDfunc IncrementaID() -> Int{ let realm = try! Realm() if let retNext = realm.objects(Roteiro.self).sorted(byKeyPath: "id").first?.id { return retNext + 1 }else{ return 1 }}
in file write use:
let Roteiro_Add = Roteiro() //increment auto id Roteiro_Add.id = Roteiro_Add.IncrementaID() Roteiro_Add.Titulo = TituloDest Roteiro_Add.Observacao = Observacao Roteiro_Add.status = false let realm = try! Realm() try! realm.write({ () -> Void in realm.add([Roteiro_Add]) })