Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a primary key to a RLMObject requires migration, any ideas how?

I'm working on an iOS app with Realm.io as the persistent store. I've just updated one of my custom RLMObject subclasses by adding a primary key.

When I run the app, I get an error telling me I need to add migration steps:

'Migration is required for object type 'MY_REALM_OBJECT' due to the following errors:
- Property 'property_name' has been made a primary key.'

I have other migration code but can't find anything in the Realm docs on how to add a primary key to an RLMObject.

Anyone know how to do this?

like image 961
Cocoadelica Avatar asked Mar 16 '23 15:03

Cocoadelica


1 Answers

I have other migration code but can't find anything in the Realm docs on how to add a primary key to an RLMObject.

You've already made it a primary key! The Realm docs covers this in the "Customizing Models" section.

Since adding/modifying a primary key to your model requires the database file to be updated (every value for that table/column in the db will be indexed), you need to update the schema version.

Primary keys are required to be unique. If all the values are already unique, Realm will automatically apply the migration for you, so you don't need to make any changes to your property_name property in the migration block.

If the property_name values are not all already unique, you'll need to make them unique in a migration block. The way you change data in a Realm migration block is to iterate over the existing objects and set values on newObject using keyed subscripting:

[RLMRealm setSchemaVersion:1
            forRealmAtPath:realmPath
        withMigrationBlock:^(RLMMigration *migration, NSUInteger oldSchemaVersion) {
  if (oldSchemaVersion < 1) {
    __block NSInteger incrementingPrimaryKeyValue = 0;
    // The enumerateObjects:block: method iterates
    // over every 'MY_REALM_OBJECT' object stored in the Realm file
    [migration enumerateObjects:@"MY_REALM_OBJECT"
                          block:^(RLMObject *oldObject, RLMObject *newObject) {

      // set the primary key to a unique value
      newObject[@"property_name"] = @(incrementingPrimaryKeyValue++);
    }];
  }
}];

To learn more about migrations, please read the "Migrations" section of the Realm docs.

like image 92
jpsim Avatar answered Apr 26 '23 03:04

jpsim