I’m dealing with a view based TableView in cocoa. In the tableview data source method I want to create three different cells based on type of object they are related to.
My idea was to create a generic id variable for the cell before the if statement and then cast it to the proper cell type inside the if when I do introspection on the object they are related to.
Unfortunately with this method xcode complains that the generic cell variable does not have the property I try to set inside. It doesn’t recognise the casting I did in the previous line.
I know this is a very basic question but what is the usual pattern to solve this problem in objective-c/cocoa.
Here is the code of the data source method:
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
GeneralVector *vector = [self.vectors objectAtIndex:row];
id cellView;
if ([[self.vectors objectAtIndex:row] isKindOfClass:[Vector class]]) {
cellView = (VectorTableCellView *)[tableView makeViewWithIdentifier:@"vectorCell" owner:self];
cellView.nameTextField.stringValue = vector.name;
} else if ([[self.vectors objectAtIndex:row] isKindOfClass:[NoiseVector class]]) {
cellView = (NoiseVectorTableCellView *)[tableView makeViewWithIdentifier:@"noiseVectorCell" owner:self];
} else {
cellView = (ComputedVectorTableCellView *)[tableView makeViewWithIdentifier:@"computedVectorCell" owner:self];
}
return cellView;
}
You don’t have to cast the assignment, since everything is by-definition a descendant of
idin Objective-C. Instead, you need to cast where you dereference the property. So, change your code to look something more like this: