Dan*_*ics 2 methods objective-c parent-child class-hierarchy alloc
在objective-C中,我希望有一个子类调用或调用父类的方法.因为在父级中已经分配了子级,并且子级执行了调用父方法的操作.像这样:
//in the parent class
childObject *newChild = [[childClass alloc] init];
[newChild doStuff];
//in the child class
-(void)doStuff {
    if (something happened) {
        [parent respond];
    }
}
我怎么能这样做?(如果你能彻底解释我会很感激)
您可以使用委托:让childClass定义委托协议和符合该协议的委托属性.然后您的示例将更改为以下内容:
// 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];
    }
}
这里有一个如何声明和使用委托协议的示例:如何设置一个简单的委托来在两个视图控制器之间进行通信?