Adrian
Adrian

Reputation: 20068

How to structure data inside Core Data for the following scenario

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

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 ?

Upvotes: 0

Views: 32

Answers (1)

Mundi
Mundi

Reputation: 80265

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.

Upvotes: 2

Related Questions