Adrian
Adrian

Reputation: 20068

Two entities inside Core Data without relationship is bad design?

I have the following entity:

class Payment: NSManagedObject {
   @NSManaged var name: String
   @NSManaged var amount: Double
}

On a given day I would have multiple payments. At the end of the day I want to take the total amount of payments and saved it somewhere:

class TotalPayment {
   @NSManaged var date: NSDate
   @NSManaged var total: Double
}

I need this because at some point I want to get the total of total payments per day for a particular period.

For example I want to take the total payments made in the last 30 days, or 100 days, so I need the sum of TotalPayment::total attribute for that period.

But I don't see how to set a relationship between these two. TotalPayment doesn't hold Payment objects, just a sum of Payment::amount.

Is this bad design ? If so, any ideas how to do it correctly ?

Upvotes: 0

Views: 60

Answers (1)

Mundi
Mundi

Reputation: 80273

You should have a date attribute in your Payment entity, and that is all you need.

To sum for a certain period, just determine the start and end dates of the period you want to sum up, then fetch with this predicate:

NSPredicate(format: "date > %@ && date < %@", startDate, endDate)

Key value coding will help you calculating the sums efficiently with great convenience.

let sum = results.valueForKeyPath("@sum.amount") as! NSNumber

Upvotes: 2

Related Questions