领域迁移失败:"需要迁移"

时间:2018-05-13 08:52:22

标签: ios objective-c realm realm-migration

我在模型中添加新属性但是一些Realm错误让我感到困惑。 我尝试的第一件事是将regDate属性(NSString)更改为NSDate类型。

RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
config.schemaVersion = 2;

config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
    NSLog(@"========== Migration executed ==========");
    if (oldSchemaVersion < 2) {
        [migration enumerateObjects:Track.className block:^(RLMObject *oldObject, RLMObject *newObject) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            newObject[@"regDate"] = [dateFormatter dateFromString:oldObject[@"regDate"]];
        }];
    }
};
[RLMRealmConfiguration setDefaultConfiguration:config];
[RLMRealm defaultRealm];

我也改变了Track.h

@property NSString *regDate;成为@property NSDate *regDate;

但是我得到了像这样的运行时错误

*** Terminating app due to uncaught exception 'RLMException',
reason: 'Migration is required due to the following errors:
- Property 'Track.regDate' has been changed from 'string' to 'date'.

原因是需要迁移。但是,迁移块从未被执行过。

我认为除了从旧的Object创建新属性并接受这个无用的regDate属性之外别无选择。

所以我改变了migrationBlock:

config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
    if (oldSchemaVersion < 2) {
        // Note: Even if you don't have to convert placeholder values,
        // you still have to provide at least an empty migration block
        // when your schema has changes to nullability of properties.
        [migration enumerateObjects:Track.className block:^(RLMObject *oldObject, RLMObject *newObject) {
            NSLog(@"========== Migration executed ==========");
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            newObject[@"n_regDate"] = [dateFormatter dateFromString:oldObject[@"n_regDate"]];
        }];
    }
};

并添加了@property NSDate *n_regDate;

错误是:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Migration is required due to the following errors:
- Property 'Track.n_regDate' has been added.

并且迁移块此时也不起作用。

我好像错过了什么。文档和错误无助于掌握正在发生的事情。

1 个答案:

答案 0 :(得分:0)

我通过将Realm 3.1.1更新为3.5.0来解决问题

我不知道这是不是一个bug。但是,如果有人使用3.1.1版,我建议更新。