ios - Realm 主键迁移 - Objective-C

标签 ios objective-c realm core-data-migration realm-migration

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

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)

然后我给 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'

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

最佳答案

要更改主键属性,您需要更改 +[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"];
          }];
      }
  }];

关于ios - Realm 主键迁移 - Objective-C ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31355878/

相关文章:

ios - 当我想在 UICollectionview 中添加一个单元格时,它会出现两个 - Swift 3

ios - GIF图片未显示

ios - 坚持一个 RLMObject

objective-c - 如何在 cocoa touch/xcode 4 中为开发人员加密我的源代码和导出

ios - Realm 创建和人口序列

java - Android Realm Arraylist 和简单的 POJO

iphone - 如何共享数据计数(Coredata 中的关系)

ios - ios 11 beta 7 的 UIKeyboardWillShowNotification 问题

ios - 呈现 Uialertview 时模糊 View Controller

ios - 如何在 iOS 的 JSQMessagecontroller 的 url 聊天中显示图像数据