views:

33

answers:

2

Hi, I have a Core Data Entity which has three properties startDate, endDate and duration. All three properties are persistent properties. I would like to know how I can calculate and update the duration property whenever the value for startDate and endDate changes?

BTW, I won't be able to make the duration as transient property since I have to use the property for sorting in my table view?

Any help is greatly appreciated

Thanks, Javid

A: 

Two options:

  • override the setters and cause the duration to be updated when the other setters are called;

  • use KVO to be notified of changes and update the duration then.

The best solution depends on your app design.

Marcus S. Zarra
A: 

If you haven't already done so, you need to let Xcode generate the Managed Object Class for your entity. If you have a look at the .m file, your properties are all declared as @dynamic. This means that any accessor methods that you don't declare will get generated dynamically.

Now you can declare custom setters for startDate and endDate, while still relying on the dynamic "get" and "primitive" methods. Primative methods are what core data uses "under the hood", but now you'll need to call them too:

- (void)setStartDate:(NSDate *)newStartDate
{
    // This part replicates what a dynamic setter would do
    [self willChangeValueForKey:@"startDate"];
    [self setPrimitiveStartDate:newStartDate];
    [self didChangeValueForKey:@"startDate"];

    // Now, calculate your new duration
    calculatedDuration = ...

    // Set the duration property
    self.duration = calculatedDuration;

}
Matt