ios - 如何将派生类方法委托(delegate)给协议(protocol)方法?

标签 ios objective-c inheritance

我是 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

您可以在 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

但是您仍然需要从 Derived

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

最后,正如其他人指出的那样,您可以使 AnotherDerived 继承自 Derived

关于ios - 如何将派生类方法委托(delegate)给协议(protocol)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45139551/

相关文章:

php - 从基类调用继承类的父方法

ios - 如何检查字符串所在的数字数组。使用swift

ios - 使用平移手势移动 CALayer 时延迟

objective-c - 检测四个手指手势(Cocoa)

objective-c - const 是在 CGFloat 之前还是之后?

javascript - Angular DI 和继承 : injecting extensions of a base service

c++ - 模板方法的接口(interface)

ios - 无法导入桥接头

ios - 将 GMT 时间对象转换为本地时间 iOS

ios - Amazon AWSS3TransferManager 在 ios 中无法上传多部分数据