Jaafar Mahdi
Jaafar Mahdi

Reputation: 713

How to give a record an specific ID in Swift Realm

I just started with Realm, and it seems pretty cool! I have almost no experience in programming, so I hope you guys can help.

I'm testing Realm out, to see what I can do, and what to expect from it.

I'm making a little app, where the user needs to type in two things. Lets say name and age. I want that piece of data to be saved into the database, and that is no problem.

I then want the user to be able to change his age(just for the sake of the example). I want my code to "target" the specific record, and update that. I have asked around, and googled, but everything I see mentions key-value pairs.

I just dont know how to add an specific ID, or how to "read" it again, and update it.

And what type should the ID be? I mean, Int? String? Float?

import RealmSwift
import Foundation

class DataClass: Object {

dynamic var name: String = ""
dynamic var age: String = "100"
dynamic var id = "" //What type?

}

Upvotes: 0

Views: 268

Answers (1)

Joshua Nozzi
Joshua Nozzi

Reputation: 61228

Have you read the documentation at all?

The Primary Key is whatever you want it to be, if you want one at all. You just have to override the primaryKey() function in your object to return the string name of the desired property (whatever that may be). The section I linked to even has an example using exactly the property name you're looking for:

class Person: Object {
  dynamic var id = 0
  dynamic var name = ""

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

I'd suggest (before "googling around") your first action should be to at least browse through the documentation of whatever API you intend to use so that you know generally how things work. If you do, you're more likely to remember not only that an answer to a basic question about the API exists, but generally where you found it. Especially if the documentation is kind enough to include so many code examples.

Upvotes: 1

Related Questions