Migrate primaryKey type?

Hi guys,

so, we have an app in production, that now needs a few changes. One issue I’m encountering is, I need to change the primaryKey type of a model from Int to String.
Right now when launching I’m getting:

Terminating app due to uncaught exception 'RLMException', reason: 'Invalid value '1' of type '__NSCFNumber' for 'string' property 'RealmProfile.id'.'

I was trying to solve this with:

if (oldSchemaVersion < 3) {
    migration.enumerateObjects(ofType: RealmProfile.className()) { oldObject, newObject in
        newObject!["id"] = "\(oldObject!["id"] ?? 1)"

but to no avail.

Any help would be really appreciated.

At first glance, 1 is not a String? Do some objects not have an id? e.g. id was optional? Wouldn’t something like this (pseudo code) work?

let oldId = oldObject![“id”] //maybe need as! Int
let newId = String(old)
newObject![“id”] = newId

That is basically what I have in my (not working) attempt in the code box.

The id was set to a fixed value before, so every old object has the id 1 so far, and it needs to be a string now.

I don’t believe that code is equivalent; your goal is to assign a string as the id instead of an int, and that line of code will assign an int - the number 1

That’s concerning as Primary Key’s must be unique so every object should not have an id of 1.

There’s nothing in your code that casts the Int value to a String so that will be needed.

Not concerning up until since there was only one object present so far, which needed to be identified from wherever. So, only with the change the objects will of course have different ids.

I don’t know why you think I’m assigning an Int in that code though, as there are string quotation marks, where I have an implicit cast of either the oldObject id or 1 to a string.

Oh - you mean a String of the Int. I thought you meant you wanted to change the type and value; e.g. an ObjectId type is often used as a primary key due to its uniqueness and self-generating nature. My apologies.

Can we see what (ofType: RealmProfile.className()) - RealmProfile.className() looks like?