最善の解決策は、self.delegate
上のプロトコルメソッドを呼び出すために、そしてそのクラスがparentDelegate上のメソッドを呼び出しています。あなたのコードはよりカプセル化されます。また、currentClassDelegate
プロトコルにparentDelegate
プロパティを追加することもできます。
しかし、あなたはそれをあなたが説明した方法を行うための十分な理由を持っている場合、これは動作します:
// Import whatever class will be used for self.delegate
#import "MarcusDelegate.h"
...
// First we make sure it's safe to cast self.delegate to MarcusDelegate
if ([self.delegate isKindOfClass:[MarcusDelegate class]]) {
id parentDelegate = [(MarcusDelegate *)self.delegate parentDelegate];
if ([parentDelegate respondsToSelector:@selector(method_I_want_to_call)]) {
[parentDelegate method_I_want_to_call];
} else {
NSLog(@"WARNING: self.delegate.parentDelegate can't handle method_I_want_to_call!");
}
} else {
NSLog(@"WARNING: self.delegate is not a MarcusDelegate object!");
}
、これは推奨される手法ではありません、なぜあなたが見ることができます。プロトコルによるプログラミングの柔軟性の一部を破壊します。他のクラスがself.delegate
に設定されていると、コードが壊れてはなりません。
これはあまりにも動作しますが、それは、プロトコルのプログラミングの柔軟性を維持する:
// in the first class
[self.delegate callThatMethodOnParent];
// then in the delegate class
- (void)callThatMethodOnParent
[self.delegate method_I_want_to_call];
}
それとも、それはプロトコルだふりを停止することができます:
@property (nonatomic, weak) MarcusDelegate *delegate;
あなたは何を意味する「コンパイラは文句?」ここで最も問題となるのは、 'x'は弱い変数ですが、この記述から知るのは難しいです。 –
@RobNapierが質問に追加されました。 – Marcus
これは、 'currentClassDelegate'プロトコルが' parentDelegate'をプロパティとして定義していないと不平を言っています。それは弱さに関連していません。 –