问题描述
我已经实现了一个带有可选方法的协议,并且在调用方法中我想在发送消息之前将 respondsToSelector:
发送到 self.delegate
,但是不编译.失败消息是:
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:
选择器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
和
//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)
IOS 5.0:(9A334), Xcode 4.2.1 (4D502)
推荐答案
-respondsToSelector:
是 NSObject 上的一个方法.要么假设您的 id
委托实际上是一个 NSObject,然后进行转换:
-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:)]
或者,更好的是,让你的委托明确地成为一个 NSObject:
Or, better, make your delegate explicitly an NSObject:
@property (nonatomic, weak) NSObject* delegate;
或者使协议成为 NSObject 的子协议:
Or make the protocol be a sub-protocol of NSObject:
@protocol MyClassDelegate <NSObject>
这篇关于self.delegate respondsToSelector: ... 无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!