【发布时间】:2015-11-07 17:10:33
【问题描述】:
我最近将我的 Realm 库从 0.92(我认为)升级到了 0.96.2,但在对“可选”属性的新支持方面遇到了一些问题。我还需要第一次进行迁移,这也使事情变得复杂。
新方案需要向其中一种数据类型添加单个字段,因此我编写了一个迁移代码,在现有对象上建立了这个新属性:
RLMRealmConfiguration* config = [RLMRealmConfiguration defaultConfiguration];
config.schemaVersion = 1;
config.migrationBlock = ^(RLMMigration* migration, uint64_t oldSchemaVersion)
{
[migration enumerateObjects:Foo.className
block:^(RLMObject* oldObject, RLMObject* newObject) {
if (oldSchemaVersion < 1)
{
newObject[@"user"] = @"";
}
}];
};
[RLMRealmConfiguration setDefaultConfiguration:config];
但是,一旦代码尝试打开领域,我就会收到一条关于可选属性类型的错误消息:
'Migration is required for object type 'Person' due to the following errors:
- Property 'name' has been made optional.
- Property ‘company’ has been made optional.
- Property 'title' has been made optional.
- Property 'phone' has been made optional.
- Property 'email' has been made optional.
- Property 'homeAddress' has been made optional.'
问题 #1 - 由于模型从“必需”属性变为“可选”,因此可以保证现有对象已经存在值;所以我很难理解为什么需要迁移。
问题 #2 - 我仍然喜欢 迁移对象,如果字符串为空,则将属性置空,因此我编写了迁移代码:
RLMRealmConfiguration* config = [RLMRealmConfiguration defaultConfiguration];
config.schemaVersion = 1;
config.migrationBlock = ^(RLMMigration* migration, uint64_t oldSchemaVersion)
{
NSLog(@"RUNNING REALM MIGRATION");
// ...basic migration of adding a new property (above)
[migration enumerateObjects:Person.className
block:^(RLMObject* oldObject, RLMObject* newObject) {
if (oldSchemaVersion < 1)
{
if ([oldObject[@"name"] length] == 0)
newObject[@"name"] = nil;
else
newObject[@"name"] = oldObject[@"name"];
// … repeat for other properties
}
}];
};
[RLMRealmConfiguration setDefaultConfiguration:config];
但是,迁移似乎没有运行; if (oldSchemaVersion < 1) 块内的断点永远不会被命中,"RUNNING REALM MIGRATION" 消息永远不会打印。
外部块——设置RLMRealmConfiguration——被击中application:didFinishLaunchingWithOptions:
【问题讨论】:
标签: objective-c realm