[英]How do I delegate derived class method to protocol method?
I am very new to Objective C. Please excuse me if you find my question very naive. 我对目标C非常陌生。如果您发现我的问题很幼稚,请原谅。 I tried searching on web, but due to lack of good context, search results don't seem to fit my requirement. 我尝试在网络上搜索,但是由于缺乏良好的背景信息,搜索结果似乎不符合我的要求。
I have a method foo
declared in protocol P
. 我有在协议P
声明的方法foo
。 interface
Derived inherit from P
and provide implementation of foo
. interface
派生自P
并提供foo
实现。 I have another interface
AnotherDerived
which inherit from protocol P
. 我有另一个interface
AnotherDerived
,它继承自协议P
I want to delegate call from method of AnotherDerived
to foo
so that Derived method gets invoked. 我想将来自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
Is there a way to do this? 有没有办法做到这一点?
Simply because two classes implement the same protocol, doesn't mean that there is some relationship between those two classes. 仅仅因为两个类实现相同的协议,并不意味着这两个类之间存在某种关系。 The foo
method in AnotherDerived
has no knowledge that there is some other class, Derived
, that also implements foo
. AnotherDerived
的foo
方法不知道还有其他类Derived
也实现了foo
。
You could allocate an instance of Derived
explicitly in AnotherDerived
's foo
and use that: 您可以在AnotherDerived
的foo
显式分配一个Derived
实例,并使用该实例:
@interface AnotherDerived: NSObject <P>
- (NSString *)foo
{
Derived *d = [Derived new];
return [d foo];
}
@end
Or you could potentially declare foo
as a class method: 或者,您可以将foo
声明为类方法:
@protocol P <NSObject>
@required
+ (NSString *)foo;
@end
@interface Derived: NSObject <P>
+ (NSString *)foo
{
return _foo;
}
@end
But you would still need to explicitly invoke foo
from Derived
但是您仍然需要从Derived
显式调用foo
@interface AnotherDerived: NSObject <P>
+ (NSString *)foo
{
return [Derived foo];
}
@end
Finally, you could make AnotherDerived
inherit from Derived
as others have pointed out. 最后,您可以像其他人指出的那样,使AnotherDerived
从Derived
继承。
If I understand correctly, your Derived
implements P
, and your AnotherDerived
is supposed to call foo
implemented in Derived
? 如果我理解正确,则您的Derived
实现P
,而您的AnotherDerived
应该调用在Derived
实现的foo
。 You need to make AnotherDerived
inherit from Derived
: 您需要使AnotherDerived
从Derived
继承:
@interface AnotherDerived: Derived
- (NSString *)foo
{
return [super foo];
}
No need to make AnotherDerived
implement P
, because Derived
already does that. 无需制作AnotherDerived
工具P
,因为Derived
已经做到了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.