0

私はこの種のコードを持っています:

MyClass.h

#import "MyOtherClass.h"

@interface MyClass : NSObject<SomeProtocol, MyOtherClassDelegate> {
...
}

MyClass.m

+ (void) doThis {
   [someObject doThisWithDelegate:self];  // someObject is MyOtherClass type
}

MyOtherClass.h :

@protocol MyOtherClassDelegate <NSObject>
@required
// Some methods
@end

- (void) doThisWithDelegate:(id<SomeOtherProtocol>)delegate;

MyOtherClass.m :

- (void) doThisWithDelegate:(id<SomeOtherProtocol>)delegate {
    if ([delegate respondsToSelector:@selector(myProtocolMethod:error:)]) do things;
}

このようにすると、コンパイル時に次の警告が表示されます

ライン上[someObject doThisWithDelegate:self];

"Incompatible pointer types sending Class to parameter of type id<SomeOtherProtocol>"

MyOtherClass.h のメソッド宣言で:

"Passing argument to parameter 'delegate' here"

以前は、id パラメーター ( id<SomeOtherProtocol>) を入力していませんでした。単に「単独」 ( id) でした。私はテストに気づいた:

if ([delegate respondsToSelector:@selector(myProtocolMethod:error:)])

FALSE を返しました (ただし、もちろんメソッドはデリゲートで実装および宣言されています)。

idそのため、コンパイル時に警告が発生するプロトコルに型を強制的に準拠させることにしました。

ここで何が起きてるの ?
このエラーが発生するのはなぜですか?また、 respondsToSelectorTRUE が返されないのはなぜですか?

4

3 に答える 3

1

まず、に準拠していることを確認してください。respondsToSelector は NSObject の一部です。

次に、delegate プロパティを効果的に設定したことを確認します。

この行:

if ([self.delegate respondsToSelector:@selector(myProtocolMethod:error:)]) 

プロパティデリゲートは myProtocolMethod:error: ... を持つべきオブジェクトを指しているので、うまくいくはずです。

おそらく、デリゲートのセッターでブレークポイントまたはテストを使用してデバッグします。

-(void)setDelegate:(id)delegate 
{
NSLog("We are setting a delegate!: %@", [delegate description]);
 _delegate = delegate;
}

アプリを実行したときに、if 行を実行した後に "We setting...." が表示される場合、またはまったく表示されない場合は、問題がどこにあるかがわかります。

于 2013-06-15T08:46:19.307 に答える