objective-c - cocoa 中的 id 变量和类型转换

标签 objective-c cocoa casting

我正在处理 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/

相关文章:

cocoa - 应用程序在启动时全屏显示

objective-c - 更改 CIFilter 的工作色彩空间

iphone - 在 iPhone 邮件应用程序上重新创建蓝色 “unread dot” 的功能

cocoa - CoreData 绑定(bind)和自定义 Cell

objective-c - 使 NSWindow 的内容变灰

c# - 转换为 C# 中的反射类型

swift - 为什么 Float 到 Double 的转换在运行时失败?

java - 这两种类型转换方式有什么区别吗?

objective-c - 我的 App Store 应用显示 "Test Ad"iAd

objective-c - 切换暗模式时自定义 NSView 背景颜色不会改变