Lets say I have an NSArrayController which contains items each with netCost and netProfit properties and I want to create a Total Percent Profit label (containing the sum of the profits divided by the sum of the costs).
In the controller class with a reference to the array controller I’ve attempted to do this as follows:
+ (NSSet *)keyPathsForValuesAffectingTotalPercentProfit {
return [NSSet setWithObjects:
@"myArrayController.arrangedObjects.@sum.netProfit",
@"myArrayController.arrangedObjects.@sum.netCost",
nil];
}
- (NSDecimalNumber *)totalPercentProfit {
NSDecimalNumber *totalProfit = [self valueForKeyPath:@"myArrayController.arrangedObjects.@sum.netProfit"];
NSDecimalNumber *totalCost = [self valueForKeyPath:@"myArrayController.arrangedObjects.@sum.netCost"];
if (!([totalCost compare:[NSDecimalNumber zero]] == NSOrderedSame)) {
return [totalProfit decimalNumberByDividingBy:totalCost];
} else {
return nil;
}
}
Yet the label bound to this totalPercentProfit property does not get refreshed when the dependent key paths are changed.
Can anybody point me in the right direction for fixing this?
Study the KVO Programming Guide, Registering Dependent Keys. You can’t observe to-many relationships this way, and you definitely can’t observe aggregates this way. Read the section on “Mac OS X v10.4 and to-many relationships on Mac OS X v10.5.”