领域迁移失败:"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 属性。

所以我改变了迁移块:

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 来解决问题

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

最新更新