gpt4 book ai didi

objective-c - 子类调用父类的方法

转载 作者:行者123 更新时间:2023-12-04 02:49:34 24 4
gpt4 key购买 nike

在 objective-C 中,我想要调用子类或调用父类的方法。因为在父级中分配了子级并且子级做了一些会调用父级方法的事情。像这样:

//in the parent class
childObject *newChild = [[childClass alloc] init];
[newChild doStuff];

//in the child class
-(void)doStuff {
if (something happened) {
[parent respond];
}
}

我该怎么做呢? (如果你能解释清楚,我将不胜感激)

最佳答案

您可以为此使用委托(delegate):让 childClass 定义委托(delegate)协议(protocol)和符合该协议(protocol)的委托(delegate)属性。然后你的例子会变成这样:

// in the parent class
childObject *newChild = [[childClass alloc] init];
newChild.delegate = self;
[newChild doStuff];

// in the child class
-(void)doStuff {
if (something happened) {
[self.delegate respond];
}
}

此处有一个如何声明和使用委托(delegate)协议(protocol)的示例:How do I set up a simple delegate to communicate between two view controllers?

关于objective-c - 子类调用父类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6169536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com