Calculated Fields

Calculated Fields

Just like lookup fields, calculated fields are virtual fields which you can add to a DADataTable object. A calculated field differs from a lookup field in that rather than looking up its value from another table based on a key, it will calculate its value using code. To demonstrate this, you will now use a calculated field to improve how this data is displayed for the Done column, which currently shows its value as integer (0, 1).

Set up the calculated field ###

You will need to set up your calculated field in the setupData method of the DataAccess class, just like you did for the lookup field, only this time you need to call the addCalculatedFieldName: dataType: target: selector: method of the DADataTable object.

//DataAccess.m
- (void)setupData {
    ...    
    [self.tasksTable addCalculatedFieldName:@"DoneText"
                                   dataType:datWideString
                                     target:self
                                   selector:@selector(calculateDoneText:)];
}
  • The addCalculatedFieldName parameter gives your calculated field a name.
  • The dataType parameter specifies the type of the new calculated field.
  • The target parameter specifies the object where the code to be run resides.
  • The selector parameter specifies the selector to the method that should actually be run to calculate the value of the field.

Based on this call, you need to add a calculateDoneText method to the DataAccess class.

//DataAccess.m
-(id)calculateDoneText:(DADataTableRow *)row {    
    BOOL done = [row[@"Done"] boolValue];
    return done ? @"Completed" : @"Still actual";
}

The code in the calculateDoneText: method is simply getting the value of the Done field in the current row (which is passed in as a parameter to the method) as a boolean value and returning a string based on its value.

DADataTableRow

This is the first time you would have seen a DADataTableRow object. Every record in a DADataTable is represented by a DADataRow. A DADataRow consists of one or more DADataField objects. An individual field within a row can be accessed with the row[@"fieldname"] syntax.

(You can actually access fields in DADataRow objects using the syntax row.fieldname if you first generate a header for the DADataTable. This is covered in another tutorial.)

Use the calculated field

Next reassign the binding for the Done column in your NSTableView to point to the DoneText field, and your table should now look like this:

Calculated Field in Action