Re: Calculations in a tableview
Re: Calculations in a tableview
- Subject: Re: Calculations in a tableview
- From: Quincey Morris <email@hidden>
- Date: Thu, 28 Jul 2011 19:13:38 -0700
On Jul 28, 2011, at 15:48, Andre Masse wrote:
> For example, lets say I have a tableview with 3 columns: quantity, unit price and total. I want to calculate total using (quantity * unit price). Pretty simple using a datasource but I've no idea how to do that with bindings (using an NSArrayController).
Well, that's the problem right there. You seem to think bindings have something to do with array controllers. They don't. (Bindings and array controllers are often used together, of course, both on the "content" side of the array controller and on the "arrangedObjects" side, but that's just a case of two things being used to complement each other.)
When working with bindings, it helps to be very diligent in thinking in terms of properties.
If you're supplying a table view's cells via bindings, then you must have a model property for *each* column. In your case, your data model is (or includes) an array property (say, "invoiceItems"), whose elements are objects (of class, say, "InvoiceItem") with properties "quantity", "unitPrice" and "totalPrice".
If the total is always calculated from the other two properties, it is typically a "derived" property (one whose value is derived on the fly, rather than actually stored), but aside from that implementation detail, there's no difference in how you use the properties to populate your table.
In code terms, the short answer to your question is:
> + (NSSet) keyPathsForValuesAffectingTotalPrice {
> return [NSSet setWithObjects: @"quantity", @"unitPrice", nil];
> }
>
> - (NSInteger) totalPrice { // or whatever the correct data type is
> return self.quantity * self.unitPrice;
> }
The second method provides the derived property value. The first method provides KVO compliance.
So how does the array controller enter this picture at all? It's a glue object (aka "mediating controller") whose function is to sort and filter the model array property. It has no role in sourcing actual data to your table***.
*** It's certainly possible to *give* it a role, but I would argue that this is a terrible idea.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden