2017-07-17 64 views
0

我對Objective C非常陌生。請原諒我,如果你發現我的問題很幼稚。我試圖在網上搜索,但由於缺乏良好的上下文,搜索結果似乎不符合我的要求。如何將派生類方法委託給協議方法?

我有一個方法foo在協議P中聲明。 interfaceP派生的繼承,並提供foo的實現。我有另一個interfaceAnotherDerived從協議P繼承。我想將來自AnotherDerived方法的調用委託給foo,以便調用Derived方法。

@protocol P <NSObject> 
@required 

- (NSString *)foo; 

@end 

@interface Derived: NSObject <P> 
- (NSString *)foo 
{ 
    return _foo; 
} 
@end 

@interface AnotherDerived: NSObject <P> 
- (NSString *)foo 
{ 
    return [super foo]; <----------------- I need something like this. It should call method of Derived 
} 
@end 

有沒有辦法做到這一點?

+0

你能否讓你的問題少一點抽象?我認爲我和P以及foo很難遵循。你能否做出更具體的解釋? – Fogmeister

+0

我很抱歉不適。我正在添加更多細節。 –

+0

致電[超級富]你的AnotherDerived應繼承衍生 –

回答

3

只是因爲兩個類實現相同的協議,並不意味着這兩個類之間有某種關係。 AnotherDerived中的foo方法不知道還有一些其他類Derived也實現foo

你可以明確地在AnotherDerivedfoo分配的Derived一個實例,並使用:

@interface AnotherDerived: NSObject <P> 
- (NSString *)foo 
{ 
    Derived *d = [Derived new]; 
    return [d foo]; 
} 
@end 

或者你可能宣佈foo作爲一個類的方法:

@protocol P <NSObject> 
@required 

+ (NSString *)foo; 

@end 

@interface Derived: NSObject <P> 
+ (NSString *)foo 
{ 
    return _foo; 
} 
@end 

但你仍然需要明確調用fooDerived

@interface AnotherDerived: NSObject <P> 
+ (NSString *)foo 
{ 
    return [Derived foo]; 
} 
@end 

最後,你可以讓AnotherDerived繼承自Derived,正如其他人指出的那樣。

+0

構圖對我來說效果很好。謝謝! –

1

如果我理解正確的,你的Derived工具P,和你的AnotherDerived應該調用Derived實施foo?你需要讓AnotherDerived繼承Derived

@interface AnotherDerived: Derived 
- (NSString *)foo 
{ 
    return [super foo]; 
} 

沒有必要讓AnotherDerived實施P,因爲Derived已經做到這一點。