在 Objective-C 中,我是否可以重写子类中父类用来遵守协议的方法?
下面提供了示例。如果我设置
id<RandomProtocol> delegate = [[B alloc] init];
A类或B类的doingSomething会被调用吗?
啊
@protocol RandomProtocol
-(NSString*)doingSomething;
@end
@interface A : NSObject <RandomProtocol>
@end
Am
#import "A.h"
@implementation A
- (NSString*) doingSomething {
return @"Hey buddy.";
}
@end
Bh
#import "A.h"
@interface B : A
@end
Bm
#import "B.h"
@implementation B
- (NSString*)doingSomething {
return @"Hey momma!";
}
@end
Example is provided below. If I set
id<RandomProtocol> delegate = [[B alloc] init];
Will doingSomething of class A or class B be called?
A.h
@protocol RandomProtocol
-(NSString*)doingSomething;
@end
@interface A : NSObject <RandomProtocol>
@end
A.m
#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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更清楚地说,将调用类 B 的 -doingSomething 实现,而不是类 A 的实现,仅仅是因为类 B 继承自类 A,并且从不调用 super 的实现。
如果您想从 B 内部调用 A 的实现,则可以在 B 的 -doingSomething 方法内添加 [super doingSomething] 行。
正如前面的答案中提到的,在协议中声明 -doingSomething 的事实在这里完全无关,因为协议的存在只是为了提供类能够执行的操作的编译时信息,以便开发人员自身的利益。
To be more clear, class B's implementation of -doingSomething will be called rather than class A's implementation, simply because class B inherits from class A, and never calls super's implementation.
If you would want to call A's implementation from inside B's, you would add in the line [super doingSomething] inside B's -doingSomething method.
As mentioned in the previous answer, the fact that -doingSomething is declared in a protocol is completely irrelevant here, as protocols simply exist for providing compile-time information of what a class is capable of doing, for the developer's own benefit.
无论 B 类的实现是否遵循协议,都将使用它。消息“doingSomething”被发送到类型“B”的类,因为这是您分配的,并且在类 B 中,“doingSomething”是运行时在类层次结构中向上移动时遇到的第一个方法。
Class B's implementation will be used regardless of whether it follows a protocol or not. The message "doingSomething" is sent to a class of type "B" because that's what you allocated, and in class B, "doingSomething" is the first method encountered by the runtime as it progresses its way up the class hierarchy.