Moritz
Moritz

Reputation: 3373

How do I set default values on new properties for existing entities after light weight core data migration?

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.

Upvotes: 30

Views: 5053

Answers (2)

Moritz
Moritz

Reputation: 3373

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.

Upvotes: 85

TechZen
TechZen

Reputation: 64428

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.

Upvotes: 1

Related Questions