The solution is not to store summary data. You can add convenience methods to your managed object subclass to deliver the desired value. Something along these lines:
func averageForPeriod(startDate: NSDate, endDate: NSDate) -> Double {
guard self.payments != nil else { return 0 }
let periodPayments = (self.payments as Set<Payment>).filter {
$0.date >= startDate && $0.date <= endDate
}
return periodPayments.valueForKeyPath("@avg.amount").doubleValue
}
NB: for comparing dates like this you need to define your own comparison function as shown here, or you can use NSTimeInterval
.