我正在处理 cocoa 中基于 View 的TableView。在表格 View 数据源方法中,我想根据它们相关的对象类型创建三个不同的单元格。
我的想法是在 if 语句之前为单元格创建一个通用 id 变量,然后当我对它们相关的对象进行内省(introspection)时,将其转换为 if 内的正确单元格类型。
不幸的是,使用这种方法时,xcode 提示通用单元变量没有我尝试在其中设置的属性。它无法识别我在上一行中所做的转换。
我知道这是一个非常基本的问题,但是在 Objective-C/cocoa 中解决这个问题的通常模式是什么。
以下是数据源方法的代码:
- (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;
}
最佳答案
您不必强制转换分配,因为根据定义,所有内容都是 Objective-C 中 id
的后代。相反,您需要在取消引用该属性的位置进行强制转换。因此,更改您的代码,使其看起来更像这样:
if( /* some check */ ) {
// No need to cast here, we are all descended from 'id'
cellView = [tableView makeViewWithIdentifier:@"vectorCell" owner:self];
// Here, we need to cast because we need to tell the compiler how to format
// the method call for the 'nameTextField' property, so it needs to know
// some information about the class
((VectorTableCellView*)cellView).nameTextField.stringValue = vector.name;
} else if( /* some other check... */ {
// and so on
}
关于objective-c - cocoa 中的 id 变量和类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11322971/