2014-09-22 160 views
1

有例子類:如何從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 

有來自委託方法調用可能實現默認?

回答

1

只需使用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; 
} 
+0

不清楚爲什麼您會爲-respondsToSelector獲得額外的分數。如果這是一種重載方法,它將起作用。如果這不是一個重載的方法,爲什麼你會首先調用超級?這兩者都可以在「代碼作者」時間靜態確定。 – 2014-09-22 05:16:24

+0

@JeffLaing NSOutlineViewDelegate協議中的方法都是可選的,所以我們不應該假設'super'採用委託協議,它必然會實現所討論的方法。也就是說,你的評論促使我更加關注這個問題 - 我沒有注意到在這種情況下超類是NSOutlineView本身。 – Caleb 2014-09-22 05:39:06

+0

我得到錯誤:OutlineViewController.m:144:12:'NSOutlineView'沒有可見的@interface聲明選擇器'outlineView:heightOfRowByItem:' – abg 2014-09-22 06:00:36