轻量级核心数据迁移后,如何为现有实体的新属性设置默认值?
我已经成功完成了核心数据模型的轻量级迁移。
我的自定义实体 Vehicle 收到了一个新属性“tirePressure”,它是 double 类型的可选属性,默认值为 0.00。
当从商店中获取“旧”车辆(在迁移发生之前创建的车辆)时,其“tirePressure”属性的值为 nil。 (这是预期的行为吗?)
所以我想:“没问题,我只需在 Vehicle 类中执行此操作:”
- (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”仍然为零。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
6个月后我终于想通了。
添加到核心数据实体的属性必须标记为非可选。
只有这样,在轻量级迁移期间才会自动为使用旧数据模型创建的实体设置默认值。
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.
您需要在
awakeFromFetch
中使用setPrimativeValueForKey
,因为self.propertyName
使用的动态访问器尚未激活。但是,由于默认值一开始就没有出现,这表明您的迁移详细失败。您可能需要创建迁移映射以确保迁移完全成功。
You need to use
setPrimativeValueForKey
inawakeFromFetch
because the dynamic accessor used byself.propertyName
is not yet active.However, since the default value is not appearing in the first place, that suggest your migration failed in detail. You may need to create a migration map to ensure the migration is completely successful.