如何从Cocoa中的子类委托方法调用超类委托方法?
问题描述:
有例子类:如何从Cocoa中的子类委托方法调用超类委托方法?
@interface OutlineViewController : NSOutlineView <NSOutlineViewDataSource, NSOutlineViewDelegate>
@end
@implementation OutlineViewController
- (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
NSTableCellView *result = nil;
if (myCondition)
{
// ...
return result;
} else {
// how return defult?
}
}
@end
有来自委托方法调用可能实现默认?
答
只需使用super
关键字来引用父类与您在您的评论完成:
if (myCondition) {
//...your implementation here
}
else {
return [super outlineView:outlineview heightOfRowByItem:item];
}
对于加分,你可以使用-respondsToSelector:
检查super
响应问题的方法。
更新:我刚刚注意到在这种情况下超类本身是NSOutlineView
本身。这非常令人困惑 - 视图和视图控制器是不同的东西,因此调用某个“视图控制器”的视图并不是一个好计划。此外,请注意,文档建议"Subclassing NSOutlineView is not recommended."
不过,我想我现在更好地理解你的问题 - 我认为,“默认实现”的意思不是继承版本的委托方法,而是大纲如果委托方法根本没有实现,将使用视图。在这种情况下,答案非常简单:您可以简单地执行NSOutlineView
本身会执行的操作。对于-outlineView:heightOfRowByItem:
文档说:
Implement this method to support an outline view with varying row heights.
对于固定的行高,而另一方面,NSOutlineView
几乎可以肯定将使用它从NSTableView
继承rowHeight
财产。因此,在不想更改行高的情况下,您可以简单地返回rowHeight
:
if (myCondition) {
//...your implementation here
}
else {
return outlineView.rowHeight;
}
不清楚为什么您会为-respondsToSelector获得额外的分数。如果这是一种重载方法,它将起作用。如果这不是一个重载的方法,为什么你会首先调用超级?这两者都可以在“代码作者”时间静态确定。 – 2014-09-22 05:16:24
@JeffLaing NSOutlineViewDelegate协议中的方法都是可选的,所以我们不应该假设'super'采用委托协议,它必然会实现所讨论的方法。也就是说,你的评论促使我更加关注这个问题 - 我没有注意到在这种情况下超类是NSOutlineView本身。 – Caleb 2014-09-22 05:39:06
我得到错误:OutlineViewController.m:144:12:'NSOutlineView'没有可见的@interface声明选择器'outlineView:heightOfRowByItem:' – abg 2014-09-22 06:00:36