schmru schmru - 3 months ago 33
iOS Question

Realm swift change primaryKey

So I have Realm object

class RegistrationPlateDB: RLMObject {

dynamic var registrationPlate : String = ""
dynamic var user : String = ""

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


and would like to change it to

class RegistrationPlateDB: Object {

dynamic var plateID : Int = -1
dynamic var registrationPlate : String = ""
dynamic var name : String = ""
dynamic var user : String = ""


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


So i've written a migration

migration.enumerate(RegistrationPlateDB.className()) { oldObject, newObject in

newObject!["name"] = ""
newObject!["user"] = ""
newObject!["registrationPlate"] = ""
newObject!["plateID"] = -1
newObject!["primaryKeyProperty"] = "plateID";
}


but I get an error probably because of the primaryKey change, since if I leave that line out it works but the primary key doesn't change.

Can someone give me any idea how to change the primaryKey.

EDIT: The first object was written for Objective-c realm

EDIT2: Or if anybody would know how could I make plateID autoincrement

Answer

Katsumi from Realm here. You don't need to attempt change primary key in the migration block.

We always automatically update the schema to the latest version, and the only thing that you have to handle in the migration block is adjusting your data to fit it (e.g. if you rename a property you have to copy the data from the old property to the new one in the migration block).

So newObject!["primaryKeyProperty"] = "plateID"; is not needed.

I think your migration block should be like the following:

migration.enumerate(RegistrationPlateDB.className()) { oldObject, newObject in
    newObject!["user"] = oldObject!["user"]
    newObject!["registrationPlate"] = oldObject!["registrationPlate"]
    newObject!["plateID"] = Int(oldObject!["registrationPlate"] as! String)
}

If you'd like to assign sequence numbers to plateID, for example:

var plateID = 0
migration.enumerate(RegistrationPlateDB.className()) { oldObject, newObject in
    newObject!["user"] = oldObject!["user"]
    newObject!["plateID"] = plateID
    plateID += 1
}
Comments