在轻量核心数据迁移后,如何为现有实体的新属性设置默认值? [英] How do I set default values on new properties for existing entities after light weight core data migration?

查看:87
本文介绍了在轻量核心数据迁移后,如何为现有实体的新属性设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的核心数据模型上成功完成轻量级迁移。



我的自定义实体Vehicle收到一个新属性tirePressure



当旧车辆从商店(在迁移之前创建的车辆)提取时,他们的轮胎压力属性为nil。 (这是预期的行为吗?)



所以我想:没问题,我只是在车辆类:

   - (void)awakeFromFetch {
[super awakeFromFetch];
if(nil == self.tirePressure){
[self willChangeValueForKey:@tirePressure];
self.tirePressure = [NSNumber numberWithDouble:0.0];
[self didChangeValueForKey:@tirePressure];
}
}

awakeFromFetch 我认为调用willChangeValueForKey和didChangeValueForKey会将'tirePresure'标记为脏。



但他们不。 >

每当这些车辆从商店提取时,tirePressure仍保持为nil,尽管已保存上下文。



添加到核心数据实体的属性必须标记为非可选的。
只有在使用旧数据模型创建的实体的轻量级迁移期间,才会自动设置默认值。


I've successfully completed light weight migration on my core data model.

My custom entity Vehicle received a new property 'tirePressure' which is an optional property of type double with the default value 0.00.

When 'old' Vehicles are fetched from the store (Vehicles that were created before the migration took place) the value for their 'tirePressure' property is nil. (Is that expected behavior?)

So I thought: "No problem, I'll just do this in the Vehicle class:"

- (void)awakeFromFetch {
    [super awakeFromFetch];
    if (nil == self.tirePressure) {
        [self willChangeValueForKey:@"tirePressure"];
        self.tirePressure = [NSNumber numberWithDouble:0.0];
        [self didChangeValueForKey:@"tirePressure"];
    }
  }

Since "change processing is explicitly disabled around" awakeFromFetch I thought the calls to willChangeValueForKey and didChangeValueForKey would mark 'tirePresure' as dirty.

But they don't.

Every time these Vehicles are fetched from the store 'tirePressure' continues to be nil despite having saved the context.

解决方案

I finally figured it out after 6 months.

The attributes that are added to a core data entity have to be marked as non-optional. Only then will the default values be set automatically during lightweight migration for the entities that were created with the old data model.

这篇关于在轻量核心数据迁移后,如何为现有实体的新属性设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆