RLMMigration如何处理跳过的架构版本

时间:2017-07-14 10:37:45

标签: objective-c realm

假设我在一个架构更新中添加了一个属性colorLenghtSort,并在下一个版本中重命名该属性以删除拼写错误:colorLengthSort

我的迁移内容如下

RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
config.schemaVersion = 25;
config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
    if(oldSchemaVersion < 24) {
        // added Hairstyle.colorLenghtSort, will be added automatically
    }
    if(oldSchemaVersion < 25) {
        // if (schema-has-property colorLenghtSort) .... <- how to get this?
        [migration renamePropertyForClass:Hairstyle.className oldName:@"colorLenghtSort" newName:@"colorLengthSort"];
    }
};
[RLMRealmConfiguration setDefaultConfiguration:config];

立即 如果用户来自schemaVersion 23或更低,则他的领域没有(拼写错误)属性,因为他跳过了V24。然后,迁移将失败:

  

由于未捕获的异常终止应用&#39; RLMException&#39;,原因:   &#39;无法重命名属性&#39; Hairstyle.colorLenghtSort&#39;因为它确实如此   不存在。&#39;

如何查看该物业是否存在?

编辑:我找到了解决方案!

if(oldSchemaVersion < 25) {

    RLMObjectSchema * oldhairstyleSchema = [[migration oldSchema] objectForKeyedSubscript:Hairstyle.className];
    bool renameNecessary = NO;
    for(RLMProperty * prop in oldhairstyleSchema.properties) {
        if([prop.name isEqualToString:@"colorLenghtSort"]){
            renameNecessary = YES;
            break;
        }
    }
    if(renameNecessary)
        [migration renamePropertyForClass:Hairstyle.className oldName:@"colorLenghtSort" newName:@"colorLengthSort"];
}

1 个答案:

答案 0 :(得分:0)

我找到了解决方案!

if(oldSchemaVersion < 25) {

    RLMObjectSchema * oldhairstyleSchema = [[migration oldSchema] objectForKeyedSubscript:Hairstyle.className];
    bool renameNecessary = NO;
    for(RLMProperty * prop in oldhairstyleSchema.properties) {
        if([prop.name isEqualToString:@"colorLenghtSort"]){
            renameNecessary = YES;
            break;
        }
    }
    if(renameNecessary)
        [migration renamePropertyForClass:Hairstyle.className oldName:@"colorLenghtSort" newName:@"colorLengthSort"];
}