【问题标题】:Call child class method from instance of parent class从父类的实例调用子类方法
【发布时间】:2013-10-21 19:17:02
【问题描述】:

我的应用程序中有大约 8 个视图控制器,每个视图控制器中都有一个功能完全相同。我希望能够将它浓缩成一个可以为所有 8 个执行任务的中心函数。该函数需要接收自身的一个实例,以便它可以在适当的视图控制器上执行任务,但是因为我没有知道正在传递哪一个,我将实例类型设置为 UIViewController *。这样,我就可以接收任何视图控制器。问题是我必须从这个方法执行一个方法,并且由于每个方法都是自定义到 UIViewController 和 im PASSING UIViewController 的那些子类,我无法从实例访问这些函数。有没有办法做到这一点?从父类的实例访问子类方法?这是一些代码:

- (void)changeIsFullscreen:(UIViewController *)viewController { // <-- Right here is the 
                           // ^^^ instance of the class that's passed to the function. I 
                           // can't pass the child because there are so many different 
                           // children that will be using it.
    if (isFullscreen == NO) {
        [viewController setIsFullscreen:YES]; // Right here is the child
                                             // class method that i need to call.
                                            // They all have the method, and if they 
                                           // don't i could use try/catch blocks to 
                                          // catch the error if there was some way to do it.
    } else {
        [viewController setIsFullscreen:NO]; // Right here is the child
                                             // class method that i need to call

    }
}

我知道一种方法是扩展 UIViewController,在那个类中创建方法,并从我刚刚扩展的新类中扩展所有其他子视图控制器。不过,我不知道这是否是完成这项任务的正确方法。是吗?还是我应该换一种方式?

【问题讨论】:

  • 你需要调用的方法叫什么名字?
  • 这是一种自定义方法。它在我发布的代码中;设置全屏。它访问一个特定于实例的变量并返回它。

标签: ios objective-c cocoa-touch inheritance


【解决方案1】:

我可能在这里遗漏了一些明显的东西,但是如果你所有的视图控制器子类都实现了这个方法,那么听起来它们应该都是从某个中间类派生的。因此,您将拥有一个派生自 UIViewController 并实现 -changeIsFiullscreen 的类,并且您的所有视图控制器都派生自 那个 类。

【讨论】:

  • 对,我实际上还没有这样做。我将不得不经历并改变它,以便他们都这样做。但是,这是一个好主意,需要完成,所以这就是不好的做法。我只是想确保这是正确的做法。谢谢你的回答。
猜你喜欢
  • 2021-08-28
  • 1970-01-01
  • 2017-11-09
  • 2012-02-22
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多