serdaryillar
serdaryillar

Reputation: 413

Realm primary key migration - objective C

Old RLMObject is there below and primaryKey is AttributeId. I want to change this key to @"Id" next build.

UserItemObject.m

@implementation UserItemObject {

}

+ ( NSString * )primaryKey; {
    return @"AttributeId";
}

@end

UserItemObject.h

@interface UserItemObject : RLMObject
   @property(nonatomic, copy) NSString *Id;
   @property(nonatomic, copy) NSString *AttributeId;
@end
RLM_ARRAY_TYPE(UserItemObject)

And then I wrote some code to AppDelegate;

  [RLMRealm setSchemaVersion:1 forRealmAtPath:[RLMRealm defaultRealmPath] withMigrationBlock:^(RLMMigration *migration, NSUInteger oldSchemaVersion) {
      if ( oldSchemaVersion < 1 ) {
          [migration enumerateObjects: UserItemObject.className block:^(RLMObject *oldObject, RLMObject *newObject) {
                newObject[ @"primaryKeyProperty" ] = @"Id";
          }];
      }
  }];

This code give me an error ;

*** Terminating app due to uncaught exception 'RLMException', reason: 'Invalid property name'

How can I solve this issue? Thanks a lot.

Upvotes: 0

Views: 899

Answers (1)

segiddins
segiddins

Reputation: 4120

To change the primary key property, you'll need to change the return value of +[UserItemObject primaryKey].

Then, to actually do the migration, you'll do:

[RLMRealm setSchemaVersion:1 forRealmAtPath:[RLMRealm defaultRealmPath] withMigrationBlock:^(RLMMigration *migration, NSUInteger oldSchemaVersion) {
      if ( oldSchemaVersion < 1 ) {
          [migration enumerateObjects: UserItemObject.className block:^(RLMObject *oldObject, RLMObject *newObject) {
                newObject[ @"Id" ] = oldObject[@"AttributeId"];
          }];
      }
  }];

Upvotes: 1

Related Questions