2016-07-12 2 views
0

私は情報を必要とするオブジェクトにデリゲートのparentDelegateのBoolを返すメソッドを呼び出したい。どのようにしてこの呼び出しメソッドを作るのですか?コンパイラは、デリゲートへの弱い参照について不平を言う。デリゲートのparentDelegateでメソッドを呼び出すにはどうすればよいですか?

x = [self.delegate.parentDelegate method_I_want_to_call];

Property parentDelegate not found on object of type __weak id <currentClassDelegate>

+0

あなたは何を意味する「コンパイラは文句?」ここで最も問題となるのは、 'x'は弱い変数ですが、この記述から知るのは難しいです。 –

+0

@RobNapierが質問に追加されました。 – Marcus

+1

これは、 'currentClassDelegate'プロトコルが' parentDelegate'をプロパティとして定義していないと不平を言っています。それは弱さに関連していません。 –

答えて

3

最善の解決策は、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; 
+1

Sterlingが書いた2番目のバージョンには間違いありません。デリゲートを持つオブジェクトは、必要なデリゲート以外のデリゲートの機能を認識してはいけません。 オブジェクトは、その代理人が別の代理人を持つことを知るべきではありません。それは、その代理人に何が伝えることができるのかだけを知るべきです。これは一方通行の通信チャネルです。 – AlexKoren

関連する問題