领域迁移失败:"Migration required"

Realm migration failure: "Migration required"

我正在向模型添加新属性,但一些 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'.

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

我认为除了从旧对象创建新的 属性 并接受这个无用的 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.

这次迁移块也没有工作。

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

我通过将 Realm 3.1.1 更新到 3.5.0 解决了问题

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