Search code examples
objective-cmacoscocoacocoa-bindingsnsarraycontroller

Creating an array item with a property that's dependent on an aggregate function on the array itself


Suppose I have an NSArrayController containing a number of 'blob' objects. These objects are displayed in a view-based NSTableView via bindings.

Now suppose that each 'blob' object contains a property called amount. For one of the NSViews in each row of the table I'd like to display amount / max_amount_in_array.

In other words, I somehow need to bind my cell to the NSArrayController's arrangedObjects.@max.amount and to the NSTableViewCell's objectValue.amount at the same time and perform my calculation.

Is there a way to handle this nicely using bindings?

Currently the only idea I have to is to have a ratio property in 'blob' and recalculate it myself every time that an object is added to the array. That's quite possible, but it just seems like there should be a more bindings-like way to solve the problem.


Solution

  • I've now done this like so:

    [libraryCell.myView bind:@"amount"
                    toObject:libraryCell
                 withKeyPath:@"objectValue.amount"
                     options:nil];
    
    [libraryCell.myView bind:@"max"
                    toObject:_librariesController
                 withKeyPath:@"arrangedObjects.@max.amount"
                     options:nil];
    

    There are thus two properties in myView (amount and max) and when either of them change I do the calculation and update the display accordingly.