0

I have the a Person object store in Core Data which contains two attributes:

  • name
  • payment

Now I decided I want to also store the average of payments for a day/month/year.

How should I store this inside Core Data ? Inside the Person object ? Create new objects ?

Adrian
  • 19,440
  • 34
  • 112
  • 219
  • 1
    Why store the average? Why not calculate it when required? – Paulw11 Dec 13 '15 at 12:14
  • Do not burden your core data stack. Your situation can be handled by creating logic in subClass (NSObject) or in view Controller(not preferred). Create a method that return float from payment attribute after making calculation on it. Use it when required. i.e. -(float) averageMonthlyPayment – Alok Dec 13 '15 at 12:22

1 Answers1

2

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.

Community
  • 1
  • 1
Mundi
  • 79,884
  • 17
  • 117
  • 140