Objective-C中的简单继承问题

发布于 2024-10-28 04:55:25 字数 718 浏览 1 评论 0原文

我有两个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫瑾少女 2024-11-04 04:55:25

[self someMessage] 会将消息“someMessage”发送到当前对象,该对象是 DerivedClass 的实例。

消息分派是在运行时动态完成的,因此它的行为将与当时的对象一样。

[self someMessage] will send the message "someMessage" to the current object, which is an instance of DerivedClass.

Message dispatch is done dynamically at run-time, so it will behave as whatever the object is at that time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文