Search code examples
core-datakey-value-observing

KVO notification with Core Data in Swift


When I generate an NSManagedObject subclass with swift, the property types are all @NSManaged, meaning I can't observe them. This is a problem when using bindings in a Cocoa application because updating the property frequently requires other properties to be 'updated'.

For example, if I add this method to my NSManagedObject subclass:

dynamic var ratePerPoint: Double {
    guard pointsPerMonth > 0 else { return 0 }

    return monthlyRate / Double(pointsPerMonth)
}

Then it's important that whenever I update the pointsPerMonth variable, which is part of the core data object, that I send a didChangeValueForKey("ratePerPoint") message.

If I don't, then the UI bindings don't update properly.


Solution

  • If ratePerPoint is a calculated property you have to implement keyPathsForValuesAffectingRatePerPoint in your NSManagedObject subclass.

    + (NSSet *)keyPathsForValuesAffectingRatePerPoint {
        return [NSSet setWithObjects:@"monthlyRate", @"pointsPerMonth", nil];
    }
    

    Documentation: Registering Dependent Keys