【问题标题】:In Objective-C, am I allowed to override a method in a subclass that the parent used to conform to a protocol?在 Objective-C 中,我是否允许在子类中重写父用于遵守协议的方法?
【发布时间】:2010-11-25 11:54:27
【问题描述】:

示例如下。如果我设置

id<RandomProtocol> delegate = [[B alloc] init];

会调用A类或B类的doingSomething吗?

啊.h

@protocol RandomProtocol

-(NSString*)doingSomething;

@end

@interface A : NSObject <RandomProtocol> 

@end

上午

#import "A.h"

@implementation A
- (NSString*) doingSomething {
    return @"Hey buddy.";
}
@end

B.h

#import "A.h"

@interface B : A
@end

B.m

#import "B.h"

@implementation B

- (NSString*)doingSomething {
    return @"Hey momma!";
}

@end

【问题讨论】:

    标签: objective-c class inheritance protocols standards-compliance


    【解决方案1】:

    无论是否遵循协议,都将使用 B 类的实现。消息“doingSomething”被发送到“B”类型的类,因为这是您分配的,而在 B 类中,“doingSomething”是运行时遇到的第一个方法,因为它在类层次结构中向上前进。

    【讨论】:

      【解决方案2】:

      更清楚地说,将调用 B 类的 -doingSomething 实现,而不是 A 类的实现,因为 B 类继承自 A 类,从不调用 super 的实现。

      如果您想从 B 内部调用 A 的实现,您可以在 B 的 -doingSomething 方法中添加 [super doingSomething] 行。

      如上一个答案中所述,在协议中声明 -doingSomething 的事实在这里完全无关紧要,因为协议只是为了提供类能够做什么的编译时信息而存在,以便开发人员自己受益。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-28
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 2012-07-02
        • 1970-01-01
        • 1970-01-01
        • 2014-12-31
        相关资源
        最近更新 更多