0

下面是旧的 RLMObject,primaryKey 是 AttributeId。我想将此键更改为@“Id”下一次构建。

用户项目对象.m

@implementation UserItemObject {

}

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

@end

用户项目对象.h

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

然后我给 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";
          }];
      }
  }];

这段代码给我一个错误;

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

我该如何解决这个问题?非常感谢。

4

1 回答 1

1

要更改主键属性,您需要更改+[UserItemObject primaryKey].

然后,要实际进行迁移,您将执行以下操作:

[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"];
          }];
      }
  }];
于 2015-07-13T02:53:08.310 回答