Objective-C中的简单继承问题
我有两个 Objective-C 类,一个是从另一个派生的,如下
@interface DerivedClass : BaseClass
{
}
所示 下面的代码部分属于 BaseClass:
- (id)init {
if (self = [super init]) {
[self configure];
}
return self;
}
- (void) configure{} //this is an empty method
而代码部分属于 DerivedClass:
-(void) configure{
NSLog(@"derived configure called");
}
现在,当我说 衍生实例 = [DerivedClass new];
并观察调用堆栈,我看到派生类的 configure
方法在基类的 init
的 [self configure]
行被调用> 方法。
我是一个 Objective-C 菜鸟,我对如何从基类的方法调用派生类的方法感到困惑。 “self
”关键字被解释为与某些语言的“this
”关键字相同,但我认为这种解释并不完全正确,对吗?
I have two Objective-C classes and one is derived from the other as
@interface DerivedClass : BaseClass
{
}
The code section below belongs to BaseClass:
- (id)init {
if (self = [super init]) {
[self configure];
}
return self;
}
- (void) configure{} //this is an empty method
And the code section belongs to the DerivedClass:
-(void) configure{
NSLog(@"derived configure called");
}
Now, when I say derivedInstance = [DerivedClass new];
and watch the call stack, I see that the configure
method of my derived class gets called at the [self configure]
line of the base's init
method.
I'm an Objective-C noob and I'm confused about how a method of a derived class gets called from the method of a base class. "self
" keyword is explained to be the same thing as "this
" keyword of some languages but I think this explanation is not completely correct, right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
[self someMessage]
会将消息“someMessage”发送到当前对象,该对象是DerivedClass
的实例。消息分派是在运行时动态完成的,因此它的行为将与当时的对象一样。
[self someMessage]
will send the message "someMessage" to the current object, which is an instance ofDerivedClass
.Message dispatch is done dynamically at run-time, so it will behave as whatever the object is at that time.