2

在 Objective-C 中,我想要一个子类调用或调用父类的方法。就像父母已经分配了孩子一样,孩子做了一些会调用父方法的事情。像这样:

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

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

我怎么能这样做呢?(如果您能详细解释一下,我将不胜感激)

4

2 回答 2

7

您可以为此使用委托:让 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];
    }
}

这里有一个如何声明和使用委托协议的示例:如何设置一个简单的委托以在两个视图控制器之间进行通信?

于 2011-05-29T18:28:45.773 回答
4

真的没什么好解释的。

为了在这种情况下使用,你有关键字super,它很像self,除了它指的是self如果它是它自己的直接超类的成员的话:

// in the child class
- (void)doStuff {
  if (something happened) {
    [super respond];
  }
}
于 2011-05-29T18:25:00.627 回答