Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

xcode - self.delegate respondsToSelector: ... does not compile

I've implemented a protocol with an optional method and in the calling method I want to send respondsToSelector: to self.delegate before I send the message, but that does not compile. The fail message is:

No Known instance method for selector 'respondsToSelector'.

As a work-around, I "sanitized" the delegate as shown below, which compiles...

//MyClass.h:

@class MyClass;

@Protocol MyClassDelegate
- (void)myClass:(MyClass *)sender willDoSomething:(BOOL)animated;
@end

@interface MyClass : UIViewController

@property (nonatomic, weak) id<MyClassDelegate> delegate;

@end

and

//MyClass.m:

...
@synthesize delegate = _delegate;
...

id sanitizedDelegate = self.delegate; //Hmmmm... why does this work?

if ([sanitizedDelegate respondsToSelector:@selector(myClass:willDoSomething:)]) {
    [self.delegate myClass:self willDoSomething:animated];
}

.

I checked a number of posts including this one but it does not answer the compilation fail issue.

Also, alternative accessors do not work...

[self delegate]
//or
_delegate

Has anyone seen this or can advise a better way of handling?

IOS 5.0:(9A334), Xcode 4.2.1 (4D502)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

-respondsToSelector: is a method on NSObject. Either assume that your id delegate is in fact an NSObject, and cast it:

[(NSObject*)self.delegate respondsToSelector:@selector(myClass:willDoSomething:)]

Or, better, make your delegate explicitly an NSObject:

@property (nonatomic, weak) NSObject<MyClassDelegate>* delegate;

Or make the protocol be a sub-protocol of NSObject:

@protocol MyClassDelegate <NSObject>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...