轻量级核心数据迁移后,如何为现有实体的新属性设置默认值?

发布于 2024-11-04 21:36:14 字数 913 浏览 0 评论 0原文

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

我的自定义实体 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巴黎夜雨 2024-11-11 21:36:14

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.

茶底世界 2024-11-11 21:36:14

您需要在 awakeFromFetch 中使用 setPrimativeValueForKey,因为 self.propertyName 使用的动态访问器尚未激活。

但是,由于默认值一开始就没有出现,这表明您的迁移详细失败。您可能需要创建迁移映射以确保迁移完全成功。

You need to use setPrimativeValueForKey in awakeFromFetch because the dynamic accessor used by self.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文