我是 Objective C 的新手。如果您觉得我的问题很幼稚,请原谅。我尝试在网上搜索,但由于缺乏良好的上下文,搜索结果似乎不符合我的要求。
我有一个方法 foo
在协议(protocol) P
中声明。 interface
派生自 P
并提供 foo
的实现。我有另一个 interface
AnotherDerived
继承自协议(protocol) P
。我想将 AnotherDerived
方法的调用委托(delegate)给 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
有办法吗?
最佳答案
仅仅因为两个类实现了相同的协议(protocol),并不意味着这两个类之间存在某种关系。 AnotherDerived
中的 foo
方法不知道还有其他类 Derived
也实现了 foo
。
您可以在 AnotherDerived
的 foo
中显式分配 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
但是您仍然需要从 Derived
foo
@interface AnotherDerived: NSObject <P>
+ (NSString *)foo
{
return [Derived foo];
}
@end
最后,正如其他人指出的那样,您可以使 AnotherDerived
继承自 Derived
。
关于ios - 如何将派生类方法委托(delegate)给协议(protocol)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45139551/