【问题标题】:Child class calls a method of the parent class子类调用父类的方法
【发布时间】:2011-09-04 09:37:21
【问题描述】:

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

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

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

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

【问题讨论】:

标签: objective-c methods parent-child class-hierarchy alloc


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    其实没什么好解释的。

    在这种情况下,您可以使用关键字super,它与self 很相似,只是它指的是self 如果它是它自己的直接超类的成员的话:

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

    【讨论】:

    • 不对——super 指的是对象的超类,而不是实例化它的对象。
    • @Simon Whitaker:他在问一个子类。当然,这不是正确的术语,但暗示他想与实例化对象交谈是一个飞跃。
    • 并非如此 - 这正是他在问题中指定的内容。 “父母已经分配了孩子,孩子做了一些会调用父母方法的事情。”同意该术语的使用不当。
    • @Simon Whitaker:这句话同样可以指代子类化和委托。
    • 其实我想要实例化对象。我不知道分配另一个对象的“正确”术语是什么。
    猜你喜欢
    • 2016-02-14
    • 2017-11-09
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多