アプリには約 8 つのビュー コントローラーがあり、それぞれにまったく同じことを行う関数があります。8つすべてのタスクを実行できる1つの中央関数に凝縮できることを望んでいました.関数は、適切なView Controllerでタスクを実行できるように、それ自体のインスタンスを受け取る必要がありますが、どちらが渡されているかを考えて、インスタンスタイプを UIViewController * として設定します。そうすれば、ビューコントローラーを受け取ることができます。問題は、このメソッドからメソッドを実行する必要があることです。各メソッドは UIViewController の子クラスにカスタム化されており、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
}
}
これを行う1つの方法は、UIViewControllerを拡張し、そのクラスでメソッドを作成し、拡張したばかりの新しいクラスから他のすべての子View Controllerを拡張することです。ただし、それがこのタスクを達成する正しい方法であるかどうかはわかりません。それは...ですか?または、別の方法で行う必要がありますか?